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和 if else 的区别
//全为if 的话 回溯的时候会判断接下来的if语句。如果为 if else 的话,回溯的时候就不会判断接下来的 else if 语句
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;
}
public static void main(String args[]){
int maze[][] = { {2,2,2,2,2,2,2},
{2,0,0,0,0,0,2},
{2,0,2,0,2,0,2},
{2,0,0,2,0,2,2},
{2,2,0,2,0,2,2},
{2,0,0,0,0,0,2},
{2,2,2,2,2,2,2} };
Maze1 maze1 = new Maze1();
maze1.goMaze1(maze);
}
}