我正在使用递归解决迷宫问题,我的矩阵如下所示。
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);
}
正如您在这里所注意到的,我正在返回一个布尔值。如果我找到了一条路径,它应该给我一个 true。但是它一直给我 false。我不确定我在 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; endY =10;
solveRecursion
的开头并监视发生的调用。然后,您就能够确定“false”发生的时间/位置。 - user2864740