point类
public class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
初始化地图与栈
public static int[][] map = {{0,0,0,0,0,0,0,0,0,0},
{0,1,1,0,1,1,1,0,1,0},
{0,1,1,0,1,1,1,0,1,0},
{0,1,1,1,1,0,0,1,1,0},
{0,1,0,0,0,1,1,1,1,0},
{0,1,1,1,0,1,1,1,1,0},
{0,1,0,1,1,1,0,1,1,0},
{0,1,0,0,0,1,0,0,1,0},
{0,0,1,1,1,1,1,1,2,0},
{0,0,0,0,0,0,0,0,0,0}};
public static Stack<Point> stack = new Stack<>();
迷宫求解主体逻辑
public static boolean mazePath(Point p){
if (p.x>map.length||p.x<0||p.y>map[0].length||p.y<0) return false;
if (map[p.x][p.y]==2){
stack.push(p);
return true;
}
if (map[p.x][p.y]!=1) return false;
stack.push(p);
map[p.x][p.y] = 3;
if (mazePath(new Point(p.x+1,p.y))||
mazePath(new Point(p.x,p.y+1))||
mazePath(new Point(p.x-1,p.y))||
mazePath(new Point(p.x,p.y-1))) return true;
map[p.x][p.y] = 4;
stack.pop();
return false;
}
运行
public static void main(String[] args) {
mazePath(new Point(1,1));
}