Sha*_*did 5 java algorithm recursion maze matrix
我正在使用递归来解决迷宫问题.我的矩阵看起来像这样
char maze[][] =
{
{'#','#','#','#','#','#','#','#','#','#','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#','#','#','#',' ','#','#','#','#','#','#'},
{'#',' ',' ',' ',' ','#',' ',' ',' ',' ','X'},
{'#',' ',' ',' ',' ','#',' ',' ',' ',' ','#'},
{'#',' ','#','#','#','#','#','#',' ','#','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#','#','#','#','#','#','#','#','#','#','#'},
};
Run Code Online (Sandbox Code Playgroud)
这是更大矩阵的原型.我的求解递归方法看起来像这样
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);
}
Run Code Online (Sandbox Code Playgroud)
你可以注意到我在这里返回一个布尔值,如果我找到一条路径,它应该给我一个真实的.但它一直在给我假.我不确定我在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;
}
Run Code Online (Sandbox Code Playgroud)
endX = 3; endY = 10;