我创建了这个程序:
package backtracking;
public class BackTracking {
public static void main(String[] args) {
//maze generation
int[][] maze = new int[4][4];
maze[0][0] = 1;
maze[0][1] = 1;
maze[0][2] = 0;
maze[0][3] = 0;
maze[1][0] = 0;
maze[1][1] = 1;
maze[1][2] = 1;
maze[1][3] = 0;
maze[2][0] = 0;
maze[2][1] = 0;
maze[2][2] = 1;
maze[2][3] = 1;
maze[3][0] = 0;
maze[3][1] = 0;
maze[3][2] = 0;
maze[3][3] = 1;
navigateMaze(maze, 0, 0);
}
public static void navigateMaze(int maze[][], int row, int column){
if(row == 3 && maze[row][column] == 1 && column == 3){
System.out.println("Success! The end was found!");
}else if(maze[row][column] == 1 && column < 3){
navigateMaze(maze, row, column++);
}else if(maze[row][column] == 0 && column > 0){
navigateMaze(maze, row++, column--);
}else if(maze[row][column] == 1 && column == 3 && row < 3){
navigateMaze(maze, row++, column);
}
}
}
它抛出StackOverflowError 在backtracking.BackTracking.navigateMaze(BackTracking.java:32) 第32行是此行:
navigateMaze(maze, row, column++);
我不确定为什么。我知道这个错误是因为递归永远不会结束,但是我不知道为什么这个会这么做。我自己检查了逻辑,似乎应该可以,但是我显然错了。