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



我有一个解决迷宫(矩阵(的项目,这很简单,但是我在使用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;
}

把语句

    maze[row][column] = 5;

紧跟在下一个(if(语句之后:

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

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

最新更新