递归迷宫算法



我正在用递归解决一个迷宫。我的矩阵是这样的

char maze[][] = 
    {
        {'#','#','#','#','#','#','#','#','#','#','#'},
        {'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
        {'#','#','#','#',' ','#','#','#','#','#','#'},
        {'#',' ',' ',' ',' ','#',' ',' ',' ',' ','X'},
        {'#',' ',' ',' ',' ','#',' ',' ',' ',' ','#'},
        {'#',' ','#','#','#','#','#','#',' ','#','#'},
        {'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
        {'#','#','#','#','#','#','#','#','#','#','#'},
    };

是大矩阵的原型。我的解递归方法是这样的

private void solve(int x, int y) {
    // set everything to false
    wasHere = new boolean[maze.length][maze[1].length];
    correctPath = new boolean[maze.length][maze[1].length];
     for (int i = 0; i < maze.length; i++){  
            // Sets boolean Arrays to default values
            for (int j = 0; j < maze[i].length; j++){
                wasHere[i][j] = false;              // set everything to false
                correctPath[i][j] = false;          
            }
     }
boolean b = solveRecursion(1,1);
System.out.println(b);
}

你可以注意到这里我返回了一个布尔值如果我找到了一个路径,它应该给我一个真值。但它一直给我错误。我不确定我在solveRecursion方法中犯的逻辑错误。这是

方法
    private boolean solveRecursion(int x, int y) {
        if (x == endX && y == endY){
            return true;
        }
        if (maze[x][y] == '#' || wasHere[x][y]){
            return false;
        }
        wasHere[x][y]=true;
        if (x != 0) // Checks if not on left edge
            if (solveRecursion(x-1, y)) { // Recalls method one to the left
                correctPath[x][y] = true; // Sets that path value to true;
                maze[x][y]='S';
                return true;
            }
        if (x != maze[0].length ) // Checks if not on right edge
                if (solveRecursion(x+1, y)) { // Recalls method one to the right
                    correctPath[x][y] = true;
                    maze[x][y]='S';
                    return true;
            }
        if (y != 0)  // Checks if not on top edge
            if (solveRecursion(x, y-1)) { // Recalls method one up
                correctPath[x][y] = true;
                maze[x][y]='S';
                return true;
           }
        if (y != maze.length) // Checks if not on bottom edge
            if (solveRecursion(x, y+1)) { // Recalls method one down
                correctPath[x][y] = true;
                maze[x][y]='S';
                return true;
            }
        return false;

}

endX = 3;恩迪= 10;

您对网格的坐标系统感到困惑。在您的示例中,X表示行数,Y表示列数。

你正在检查if (y != maze.length),如果是,你移动"向下一个",实际上是移动到右边一个,而不是向下一个。

这种混乱使您的Y坐标受到X值的限制。

你应该把这一行改成:

 if (y != maze[0].length)

这样就能解决问题了。你永远不会到达值(3,9),它离结束只有1个距离,因为你的if语句检查坐标(8,9)并说:

 if (y != maze.length) // Hmm. my coordinates are (8,9) so y = 9. 
                       // maze.length is 9, so this is false.

最新更新