如果关于矩阵单元格的语句没有返回true(java)

时间:2017-05-15 17:19:59

标签: java arrays if-statement matrix

我有一个用于解决迷宫(矩阵)的类的项目,这很简单,但是我在if语句中遇到了一些麻烦,应该验证矩阵单元的可用性,看看如果该号码是路径的一部分。

这是我创建的测试迷宫:

    // 0 = start
    // 1 = path
    // 2 = wall
    // 3 = end
    // 5 = tried
    // 6 = final path

int [][] maze = {{2,2,2,0,2,2,2,2,2,2},
                {2,2,2,1,2,2,1,1,1,2},
                {2,2,2,1,2,2,2,2,1,2},
                {2,2,2,1,2,2,2,1,1,2},
                {2,2,1,1,2,2,1,2,1,1},
                {2,1,1,0,2,2,2,2,2,2},
                {2,1,2,0,2,2,2,2,2,2},
                {2,1,1,0,2,2,2,2,2,2},
                {2,2,3,0,2,2,2,2,2,2},};

以下是检查当前单元格是否有效的方法:

private boolean valid (int row, int column) {

    boolean result = false;

    // checks if cell is inside of the matrix
    if (row >= 0 && row < maze.length &&
            column >= 0 && column < maze[0].length) {

        //  checks if cell is not blocked, if it has previously been tried or it's the end
        if (maze[row][column] == 1 || maze[row][column] == 3 || maze[row][column] == 0 || maze[row][column] == 5) {
            result = true;
        }else{

            result = false;
        }
    }

    return result;

}

从使用打印语句我已经看到问题可能在嵌套的if语句中。但是可能还有另一个我不确定的问题,那就是解决方法。

public boolean solve(int row, int column ) {

    boolean solved = false;

    if (valid(row, column)) {

        maze[row][column] = 5;

        if (maze[row][column] == 1 || maze[row][column] == 0){
            if( !solved){//it's going to call the function it self and move if possible.
                solved = solve(row + 1, column);  // South
                if (!solved)
                    solved = solve(row, column + 1);  // East
                if (!solved)
                    solved = solve(row - 1, column);  // North
                if (!solved)
                    solved = solve(row, column - 1);  // West
            }
            if (solved)  // part of the final path
                maze[row][column] = 7;
        }else if (maze[row][column] == 3) {
            solved = true;
            System.out.println("lol the end");
        }
        //exception here not to leave the maze and case there's no 0
    }
    return solved;
}

1 个答案:

答案 0 :(得分:0)

发表声明

    maze[row][column] = 5;

在下一个(if)语句之后:

    if (maze[row][column] == 1 || maze[row][column] == 0){

因为它可以保护以正确评估此if语句中的条件。