1)findWay方法是为了找出走出迷宫的路径,找到返回true,否则返回false
2)(i,j)是老鼠的位置,初始化的位置为(1,1)
3)因为是递归找路,所以先规定map数组的各个值含义:
0表示可以走 1表示障碍物 2表示可以走 3表示走过但走不通
4)但map[6][5]==2就说明找到通路,可以结束,否则继续找
5)先确定找路策略 下->右->上->左(ps:找路策略会影响找到的通关路径)
代码如下:
//2024.07.09
public class MiGong {
public static void main(String[] args) {
int[][] map = new int[8][7];
//0-can go, 1-not can go
/*
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (i == 0 || i == 7 || j == 0 || j == 6) {
map[i][j] = 1;
}
}
}
*/
for (int i = 0; i < 7; i++) {
map[0][i] = 1;//1 row
map[7][i] = 1;//8 row
}
for (int i = 0; i < 8; i++) {
map[i][0] = 1;//1 column
map[i][6] = 1;//7 column
}
//图示1
map[3][1] = 1;
map[3][2] = 1;
map[4][3] = 1;
//图示2
// map[2][1] = 1;
// map[2][2] = 1;
// map[1][2] = 1;
T t1 = new T();
t1.findWay(map, 1, 1);
//Output current map
System.out.println("==========current map==========");
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
}
class T {
public boolean findWay(int[][] map, int i, int j){
if (map[6][5] == 2) {
return true;
}else{
if(map[i][j] == 0){
map[i][j] = 2;
if (findWay(map, i + 1, j)) {
return true;
}else if (findWay(map, i, j + 1)) {
return true;
}else if (findWay(map, i - 1, j)) {
return true;
}else if (findWay(map, i, j - 1)) {
return true;
}else{
map[i][j] = 3;
return false;
}
}else{ //map[i][j] = 1, 2, 3
return false;
}
}
}
}
图示1运行截图:
图示2运行截图: