【算法】BFS寻迷宫最短步数

32 篇文章 0 订阅

BFS走四方

import java.util.LinkedList;
import java.util.Queue;

public class Main {
    //方向
    static final int[][] next = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
    //迷宫
    static int[][] map = {
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 1, 1, 1, 0},
            {0, 0, 1, -1, 0, 0},
            {0, 0, 1, 0, 0, 0},
    };
    //标记
    static int[][] book = {
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
    };
    //队列
    static Queue<Integer[]> queue = new LinkedList<>();
    //每个点距离起点的距离
    static int dis[][] = new int[6][6];
    public static void main(String[] args) {
        bfs(0, 0);
        //打印标记
//        for (int i = 0; i < book.length; i++) {
//            for (int j = 0; j < book[0].length; j++) {
//                System.out.print(book[i][j] + " ");
//            }
//            System.out.println();
//        }
    }

    static void bfs(int x, int y) {
        if (map[x][y] == -1) {
            return;
        }
        //起点距离起点距离为0
        dis[x][y] = 0;
        //将起点入队
        queue.offer(new Integer[]{x, y});
        while (!queue.isEmpty()) {
            //出队
            Integer[] cur = queue.poll();
            //走四方
            for (int i = 0; i < 4; i++) {
                int xx = cur[0] + next[i][0];
                int yy = cur[1] + next[i][1];
                if (xx >= 0
                        && xx < map.length
                        && yy >= 0
                        && yy < map[0].length
                        && book[xx][yy] != 1
                        ) {
                    //标记
                    book[xx][yy] = 1;
                    //几点当前点距离起点的距离
                    dis[xx][yy] = dis[cur[0]][cur[1]] + 1;
                    //到达目标点
                    if (map[xx][yy] == -1) {
                        //System.out.printf("{%s, %s} %s\n", xx, yy, map[xx][yy]);
                        //打印目标点距离起点的最小距离
                        System.out.println("minDis:"+dis[xx][yy]);
                        return;
                    }
                    //System.out.printf("{%s, %s} %s\n", xx, yy, map[xx][yy]);
                    //入队
                    queue.offer(new Integer[]{xx, yy});
                }
            }

        }

    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值