代码
public class Main {
public static void main(String[] args) {
int[][] maze = new int[7][8];
for (int i = 0;i < 8;i++){
maze[0][i] = 1;
maze[6][i] = 1;
}
for (int i = 0;i < 7;i++){
maze[i][0] = 1;
maze[i][7] = 1;
}
maze[3][1] = 1;
maze[3][2] = 1;
System.out.println("迷宫的初始状态为:");
for (int[] i : maze){
for (int j : i){
System.out.print(j + " ");
}
System.out.println();
}
setWay(maze,1,1);
System.out.println("迷宫的最后状态为:");
for (int[] i : maze){
for (int j : i){
System.out.print(j + " ");
}
System.out.println();
}
}
public static boolean setWay(int[][] maze,int i,int j){
if(maze[5][6] == 2){
return true;
}else {
if (maze[i][j] == 0){
maze[i][j] = 2;
if (setWay(maze,i + 1,j)){
return true;
}else if (setWay(maze,i,j + 1)){
return true;
}else if (setWay(maze,i - 1,j)){
return true;
}else if (setWay(maze,i,j - 1)){
return true;
}else {
maze[i][j] = 3;
return false;
}
}else {
return false;
}
}
}
}
结果1
迷宫的初始状态为:
1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 1 1 0 0 0 0 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1
迷宫的最后状态为:
1 1 1 1 1 1 1 1
1 2 0 0 0 0 0 1
1 2 2 2 0 0 0 1
1 1 1 2 0 0 0 1
1 0 0 2 0 0 0 1
1 0 0 2 2 2 2 1
1 1 1 1 1 1 1 1
结果2
迷宫的初始状态为:
1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 1
1 0 0 1 0 0 0 1
1 1 1 0 0 0 0 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1
迷宫的最后状态为:
1 1 1 1 1 1 1 1
1 2 2 2 2 0 0 1
1 2 2 1 2 0 0 1
1 1 1 0 2 0 0 1
1 0 0 0 2 0 0 1
1 0 0 0 2 2 2 1
1 1 1 1 1 1 1 1
结果3
迷宫的初始状态为:
1 1 1 1 1 1 1 1
1 0 0 1 0 0 0 1
1 0 0 1 0 0 0 1
1 1 1 0 0 0 0 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1
迷宫的最后状态为:
1 1 1 1 1 1 1 1
1 3 3 1 0 0 0 1
1 3 3 1 0 0 0 1
1 1 1 0 0 0 0 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1