package 数据结构.递归;
/**
* Created with IntelliJ IDEA.
*
* @Author: 你的名字
* @Date: 2021/09/09/17:57
* @Description:
*/
public class MiGong {
public static void main(String[] args) {
int[][] map=new int[8][7];
//将第1列和第7列的值都置为1
for (int i = 0; i <8; i++) {
map[i][0]=1;
map[i][6]=1;
}
map[3][1]=1;
map[3][2]=1;
//将第1行和第8行的值置为1
for (int i = 0; i <7 ; i++) {
map[0][i]=1;
map[7][i]=1;
}
//打印map
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map[i][j]+" ");
}
System.out.println();
}
//从map[1][1]开始走
setWay(map,1,1);
//走完之后打印迷宫
System.out.println("从map[1][1]开始走");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map[i][j]+" ");
}
System.out.println();
}
}
public static boolean setWay(int[][] map,int i,int j){
if(map[6][5]==2){//已经找到通路
return true;
}else {
if(map[i][j]==0){
//假定该点可以走通
map[i][j]=2;
if(setWay(map,i+1,j)){//向下走
return true;
}else if(setWay(map,i,j+1)){//向右走
return true;
}else if(setWay(map,i-1,j)){//向上走
return true;
}else if(setWay(map,i,j-1)){//向左走
return true;
}else{//走不通
map[i][j]=3;
return false;
}
}else{
return false;
}
}
}
}
运行结果:
1 1 1 1 1 1 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 1 1 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 1 1 1 1 1 1
从map[1][1]开始走
1 1 1 1 1 1 1
1 2 0 0 0 0 1
1 2 2 2 0 0 1
1 1 1 2 0 0 1
1 0 0 2 0 0 1
1 0 0 2 0 0 1
1 0 0 2 2 2 1
1 1 1 1 1 1 1