java利用递归与栈实现简单的迷宫求解算法

point类

public class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

初始化地图与栈

/**
     * 0,墙
     * 1,可走通道
     * 2,终点
     * 3,在当前路径上的通道块,即在栈内的通道块
     * 4,被标记为不通的通道块,即四个方向都不通
     * */
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));
}
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页