leetcode505 迷宫2

https://leetcode-cn.com/problems/the-maze-ii/
区别于普通的BFS,这道题的特点是。一路走到头才停下来选择接下来该怎么走。普通的BFS是一步一步的走。所以这里要用到优先队列,保证每一步走的都是当前距离的最小的那个方向的选择(贪心)。

class Solution {
    int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};

    public int shortestDistance(int[][] maze, int[] start, int[] destination){
        if(maze == null || maze.length == 0 || maze[0].length == 0){
            return -1;
        }

        int m = maze.length;
        int n = maze[0].length;
        boolean[][] v = new boolean[m][n];
        PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[2]-b[2]);
        pq.add(new int[]{start[0],start[1],0});

        while(!pq.isEmpty()){
            int[] cur = pq.poll();

            if(v[cur[0]][cur[1]]){
                continue;
            }
            v[cur[0]][cur[1]] = true;
            if(cur[0]==destination[0] && cur[1]==destination[1]){
                return cur[2];
            }

            for(int[] dir : dirs){
                int r = cur[0];
                int c = cur[1];
                int step = 0;
                while(r+dir[0]>=0 && r+dir[0]<m && c+dir[1]>=0 && c+dir[1]<n && maze[r+dir[0]][c+dir[1]]==0){
                    r += dir[0];
                    c += dir[1];
                    step++;
                }
                pq.add(new int[]{r,c,cur[2]+step});
            }
        }
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值