整个迷宫算法代码为
public class Maze1 { public int entrancei = 1;//入口坐标 public int entrancej = 1; public int existi = 5;//出口坐标 public int existj = 5; public int success = 0; public void goMaze1(int maze[][]){ //显示迷宫 for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) { System.out.print(maze[i][j]); } System.out.println(); } // 显示路径 if (testMaze1(maze, entrancei, entrancej) == 1) { System.out.println("找到路径"); for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) { System.out.print(maze[i][j]); } System.out.println(); } }else { System.out.println("没找到路径"); } } // 测试当前路径是否能走通 public int testMaze1(int maze[][], int i, int j) { maze[i][j] = 1; if (i == existi && j == existj) success = 1; // 向下走 if (success == 0 && maze[i][j + 1] == 0) testMaze1(maze, i, j + 1); else if (success == 0 && maze[i + 1][j] == 0) testMaze1(maze, i + 1, j); else if (success == 0 && maze[i][j - 1] == 0) testMaze1(maze, i , j - 1); else if(success == 0 && maze[i - 1][j] == 0) testMaze1(maze, i - 1, j); if (success != 1) maze[i][j] = 0; return success; }
整个回溯过程失败。但是将测试路径函数中的判断语句改为
public int testMaze1(int maze[][], int i, int j) { maze[i][j] = 1; if (i == existi && j == existj) success = 1; // 向下走 if (success == 0 && maze[i][j + 1] == 0) testMaze1(maze, i, j + 1); if (success == 0 && maze[i + 1][j] == 0) testMaze1(maze, i + 1, j); if (success == 0 && maze[i][j - 1] == 0) testMaze1(maze, i , j - 1); if(success == 0 && maze[i - 1][j] == 0) testMaze1(maze, i - 1, j); if (success != 1) maze[i][j] = 0; return success; }
则回溯成功。。我想问下各位大神这是什么情况。。if else判断语句在这种情况下回溯时有什么不同
else if 只能走一个条件
而if能走多个条件