【问题标题】:If statement concerning matrix cell not returning true(java)如果有关矩阵单元的语句不返回 true(java)
【发布时间】:2017-05-15 17:19:58
【问题描述】:

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

}

通过使用 print 语句,我发现问题可能出在嵌套的 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;
}

【问题讨论】:

  • 这就是调试器存在的原因。我会花一些时间学习如何使用 IDE 的调试器。
  • 嗯,它比较一次,如果不是一切都是真的,它会返回假
  • 我还没有测试过,但是,当您调用此行 maze[row][column] = 5; 时,当您到达此行时,如果:if (maze[row][column] == 1 || maze[row][column] == 0){ 它总是错误的......(if (5 != 0 OR 5 != 1),就是这样说)或者我错过了什么......?
  • 你传递了哪一行和哪一列,你期望返回 true 而它返回 false?

标签: java arrays if-statement matrix


【解决方案1】:

发表声明

    maze[row][column] = 5;

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2022-01-01
    相关资源
    最近更新 更多