现有一个9*9的迷宫格子,我们需要从Enter找到Exit,将其存入一个9*9的二维数组内,0代表可以通过的路,1代表墙(不可通行)
同时我们在创建一个9*9的二位布尔数组,进行后续返回用
进入迷宫(1,0)开始循环方向看是否有墙(循环顺序为上、右、下、左),若能通过则在布尔数组内返回为true
循环遍历可行后入栈
如果走到 (1,3)上、下‘、左都遍历完后且无法通行,返回至(1,4),且(1,4)之前通过(布尔数组内为true),则弹栈且返回false表示此路已经走过。
不断循环此过程,代码如下:
public class Maze {
private static int[][] maze = {
{1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 1, 0, 0, 0, 1, 1, 1},
{1, 0, 1, 1, 1, 0, 1, 1, 1},
{1, 0, 0, 1, 0, 0, 1, 1, 1},
{1, 1, 0, 1, 1, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1, 0, 1},
{1, 0, 1, 1, 1, 0, 0, 0, 1},
{1, 1, 0, 0, 0, 0, 1, 0, 0},
{1, 1, 1, 1, 1, 1, 1, 1, 1}
};
//入口信息
private static int entryX = 1;
private static int entryY = 0;
//出口信息
private static int exitX = 7;
private static int exitY = 8;
//路径访问状态表
private static boolean[][] visited = new boolean[9][9];
//方向变化量
private static int[][] direction = {
{-1, 0}, {0, 1}, {1, 0}, {0, -1}
};
//存储路径的栈
private static LinkedList<String> stack = new LinkedList<>();
public static void main(String[] args) {
boolean flag = go(entryX,entryY);
if (flag) {
for (String path: stack) {
System.out.println(path);
}
}else {
System.out.println("迷宫不通");
}
}
//以x, y为入口 看是否能够同时向下找到出口 返回false找不到
private static boolean go(int x, int y) {
stack.push("(" + x + " , " + y + ")");
visited[x][y] = true;
if (x == exitX && y== exitY){
return true;
}
//考虑四个方向 上 右 下 左的顺序
for (int i = 0; i < direction.length; i++) {
int newX = direction[i][0] + x;
int newY = direction[i][1] + y;
if (isInArea(newX, newY) && isRoad(newX, newY) && !visited[newX][newY]){
if (go(newX, newY)){
return true;// 某一个反向能通 则向上返回true 表示此层x, y 能通
}
}
}
stack.pop();
return false; //四个方向都不通 则向上返回false 表示此层x, y不通
}
private static boolean isRoad(int x, int y) {
return maze[x][y] == 0;
}
private static boolean isInArea(int x, int y) {
return x >= 0 && x < 9 && y >= 0 && y < 9;
}
}