leetcode 二进制矩阵中的最短路径

题目链接
思路:BFS
就是一个朴素的BFS就可以出来,定义一个二维数组,每个[i][j]表示到这个位置的最小路径长度
初始化nums二维数组,这个数组就是上面说的用来存到达每个位置的最小的路径长度,nums[0][0]=1,那么后面的就是前面的+1。
代码中都有注释。
代码:

class Solution {

    int[][] fx = {
            {1,0},
            {0,1},
            {-1,0},
            {0,-1},

            {1,-1},
            {-1,1},
            {1,1},
            {-1,-1},
    };//八个方向
    int[][] nums = null;
    int n = 0;
    public int shortestPathBinaryMatrix(int[][] grid) {
        n = grid.length;
        if(grid[0][0]==1 || grid[n-1][n-1]==1){
            return -1;
        }

        if(n==1){
            return grid[0][0] == 0 ? 1 : -1;
        }

        nums = new int[n][n];
        //初始化最大的路径长度
        for(int i = 0 ; i < n ;i++){
            for(int j = 0; j < n;j++){
                nums[i][j] = Integer.MAX_VALUE;
            }
        }
        //初始化当前的步长
        nums[0][0] = 1;
        //广搜的队列
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{0,0});
        //进行广搜
        bfs(grid, queue);

        return nums[n-1][n-1] == Integer.MAX_VALUE ? -1 : nums[n-1][n-1];
    }

    public void bfs(int[][] grid, Queue<int[]> queue){
        Queue<int[]> afterQueue = new LinkedList<>();
        //遍历队列
        while (!queue.isEmpty()){

            int[] curPoint = queue.poll();

            if(curPoint[0]==n-1 &&curPoint[1]==n-1){
                return;
            }
            //向八个方向遍历
            for(int[] f : fx){
                int nextx = curPoint[0] + f[0];
                int nexty = curPoint[1] + f[1];
                if(nextx < 0 || nextx >=n || nexty < 0 || nexty >=n || grid[nextx][nexty]==1){
                    continue;
                }
                if(nums[nextx][nexty] == Integer.MAX_VALUE){
                    afterQueue.add(new int[]{nextx,nexty});
                    //更新下一个单元格的最小路径长度
                    nums[nextx][nexty] =  nums[curPoint[0]][curPoint[1]] + 1;
                }
            }
        }
        //如果从 前一个队列 没有一个点可以深搜,那么就结束了
        if(!afterQueue.isEmpty()){
            bfs(grid,afterQueue);
        }
    }
}

好好学习。
不打扰是我的温柔。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值