分支回溯——迷宫问题

现有一个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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值