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

package leetcode.search;

import javafx.util.Pair;

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

public class MinPathLength {
    int solution(int[][] grids,int tr,int tc){
        final int[][] direction= {{1,0},{-1,0},{0,1},{0,-1}};
        int maxRow = grids.length;
        int maxColumn = grids[0].length;
        Queue<Pair<Integer,Integer>> queue  = new LinkedList<>() ;

        queue.add(new Pair<>(0,0));
        int pathLength = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            pathLength++;//确定了下一步在+1
            while (size-->0){//先找到确定没问题的一步,因为肯定是多种混合的道路
                Pair<Integer,Integer> p  = queue.poll();

                int key = p.getKey();
                int value = p.getValue();
                grids[key][value] = 0;//标记为已经走过
                for (int[] i : direction){
                    int nr = key + i[0];
                    int  cr =value+ i[1];
                    if (nr<0||cr<0||nr>=maxRow||cr>=maxColumn||grids[nr][cr]==0){
                        continue;//越界
                    }
                    if (nr ==tr&&cr==tc){
                        return  pathLength;

                    }
                    queue.add(new Pair<>(nr,cr));
                }
            }

        }
        return -1;
    }

    public static void main(String[] args) {
        new MinPathLength().solution(new int[][]{{1,1,0,1}, {1,0,1,0}, {1,1,1,1}, {1,0,1,1}},3,3);
    }

}

size-->0 先判断size>0 再减1,相反的是--size,先减再判断

两个while循环,确定下一步的走法,理解还不是很深刻

int[][] direction 对4个方向的设计

Pair常用的键值对的存储数据结构

Queue可以new LinkedList, PriorityQueue等等

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值