BFS,计算在网格中从原点到特定点的最短路径长度,

如下,二维数组,求从第一个点(0,0)到某个特定点(tr,tc)的最短路径长度。
代码中有详细的注释
二维数组:
[
 [1,1,0,1],
 [1,0,1,0],
 [1,1,1,1],
 [1,0,1,1]
]
其中:
1表示可以经过某个位置,0代表此位置不可走,求解从 (0, 0) 位置到 (tr, tc) 位置的最短路径长度。
    代码:
    public static int minPathLength(int[][] grids, int tr, int tc) {
        if(grids.length<=0 || grids[0].length<=0
                || tr<0 || tc < 0)
            return -1;
        //direction中分别代表右移,左移,上移,下移
        final int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        //m代表有多少行,n代表多少列
        final int m = grids.length, n = grids[0].length;
        //queue用来存储接下来要遍历到的点
        //Pair存储当前点的坐标
        Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
        //首先将0,0点入队列
        queue.add(new Pair<>(0, 0));
        //此时没有移动,所以长度为0
        int pathLength = 0;
        //当队列不为空的时候
        while (!queue.isEmpty()) {
            //size的作用为检测当前queue里面有多少个值,也就代表着走一步可以到达的点有多少个
            int size = queue.size();
            //每一次循环,pathLength会加一
            pathLength++;
            //就执行size次循环
            while (size-- > 0) {
                Pair<Integer, Integer> cur = queue.poll();
                for (int[] d : direction) {
                    int nr = cur.getKey() + d[0], nc = cur.getValue() + d[1];
                    Pair<Integer, Integer> next = new Pair<>(nr, nc);
                    //判断下一步是否越界
                    if (next.getKey()<0 || next.getValue()>=m
                            || next.getKey() >= n || next.getValue()<0) {

                        continue;
                    }
                    //判断当前点的值是否为0,为0代表不可以走
                    if(grids[next.getKey()][next.getValue()] ==0){
                        continue;
                    }
                    grids[next.getKey()][next.getValue()] = 0; // 标记
                    if (next.getKey() == tr && next.getValue() == tc) {
                        return pathLength;
                    }
                    queue.add(next);
                }
            }
        }
        return -1;
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值