我的代码的目的是创建一个程序,该程序将在迷宫中读取并将其存储到二维数组中并解决它。我让程序读取迷宫并将其放入数组中,但我的递归算法不起作用,这是我第三次更改它以使其工作。那么你能帮我让它工作吗?
编辑:我发现我的原始算法存在问题,因为我得到它来解决迷宫,但我遇到了另一个问题。该程序没有打印出正确的东西。这也只是出于我的好奇心。我已经找到了如何让它以另一种方式工作。
迷宫代码:
public static boolean goNorth(){
boolean success;
if (maze[currCol][currRow - 1] == maze[finishCol][finishRow]) {
success = true;
}
if(maze[currCol][currRow - 1] == CLEAR){
maze[currCol][currRow - 1] = PATH;
currRow = currRow - 1;
success = goNorth();
if(!success){
success = goWest();
if(!success){
success = goEast();
if(!success){
maze[currCol][currRow] = VISITED;
currRow = currRow + 1;
}
}
}
return success;
} else {
return false;
}
}
public static boolean goWest(){
boolean success;
if (maze[currCol - 1][currRow] == maze[finishCol][finishRow]) {
success = true;
}
if(maze[currCol - 1][currRow] == CLEAR){
maze[currCol - 1][currRow] = PATH;
currCol = currCol - 1;
success = goWest();
if(!success){
success = goSouth();
if(!success){
success = goNorth();
if(!success){
maze[currCol][currRow] = VISITED;
currCol = currCol + 1;
}
}
}
return success;
} else {
return false;
}
}
public static boolean goEast(){
boolean success;
if (maze[currCol + 1][currRow] == maze[finishCol][finishRow]) {
success = true;
}
if(maze[currCol + 1][currRow] == CLEAR){
maze[currCol + 1][currRow] = PATH;
currCol = currCol + 1;
success = goEast();
if(!success){
success = goNorth();
if(!success){
success = goSouth();
if(!success){
maze[currCol][currRow] = VISITED;
currCol = currCol - 1;
}
}
}
return success;
} else {
return false;
}
}
public static boolean goSouth(){
boolean success;
if (maze[currCol][currRow + 1] == maze[finishCol][finishRow]){
success = true;
}
if(maze[currCol][currRow + 1] == CLEAR){
maze[currCol][currRow + 1] = PATH;
currRow = currRow + 1;
success = goSouth();
if(!success){
success = goEast();
if(!success){
success = goWest();
if(!success){
maze[currCol][currRow] = VISITED;
currRow = currRow - 1;
}
}
}
return success;
} else {
return false;
}
}
}
迷宫求解器代码:
public class SolveMaze1
{
public static void main (String[] args)
{
Maze1 maze = new Maze1();
maze.readMaze();
maze.printMaze();
maze.goNorth();
maze.printMaze();
}
}
期望的结果:
xxxxxxxxxxxxxxxxxxFx
x x xxxx x
x xxxxx xxxxx xx x
x xxxxx xxxxxxx xx x
x xx xx x
x xxxxxxxxxx xx x
xxxxxxxxxxxxSxxxxxxx
xxxxxxxxxxxxxxxxxxFx
xVVVVVxPPPPPPPxxxxPx
xVxxxxxPxxxxxPPPxxPx
xVxxxxxPxxxxxxxPxxPx
xVVVVVVPPPPPPxxPxxPx
xVxxxxxxxxxxPxxPPPPx
xxxxxxxxxxxxSxxxxxxx
我的结果:
xxxxxxxxxxxxxxxxxxFx
xVVVVVxVVVVVVVxxxxVx
xVxxxxxVxxxxxVVVxxVx
xVxxxxxVxxxxxxxVxxVx
xVVVVVVVVVVVVxxVxxVx
xVxxxxxxxxxxVxxVVVVx
xxxxxxxxxxxxSxxxxxxx