The Maze II

13 篇文章 0 订阅
Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4)

Output: 12

Explanation: One shortest way is : left -> down -> left -> down -> right -> down -> right.
             The total distance is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.

思路:核心思想就是,到达同一个点的时候,step可能不一样,那么我们必须要有一个数据结构去sort一下,每次取最小的step,然后继续往下走,那么这里就是需要PQ,这题考的是Dijkstra (dai ka stra) Algorithm,步骤跟BFS有点不一样的地方是,收集下一层的时候,不能visite = false 就直接赋值visite = true, 那样会漏掉到同样一个点的最小距离;(update its priority if it was already in the pq);

class Solution {
    class Node {
        public int x;
        public int y;
        public int step;
        public Node(int x, int y, int step) {
            this.x = x;
            this.y = y;
            this.step = step;
        }
    }
    
    public int shortestDistance(int[][] maze, int[] start, int[] destination) {
        int m = maze.length;
        int n = maze[0].length;
        boolean[][] visited = new boolean[m][n];
        PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (a.step - b.step));
        pq.offer(new Node(start[0], start[1], 0));
        
        int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};
        while(!pq.isEmpty()) {
            Node node = pq.poll();
            if(node.x == destination[0] && node.y == destination[1]) {
                return node.step;
            }
            if(visited[node.x][node.y]) {
                continue;
            }
            visited[node.x][node.y] = true;
            for(int[] dir: dirs) {
                int nx = node.x;
                int ny = node.y;
                int step = node.step;
                while(isvalid(nx + dir[0], ny + dir[1], maze)) {
                    nx += dir[0];
                    ny += dir[1];
                    step++;
                }
                pq.offer(new Node(nx, ny, step));
            }
        }
        return -1;
    }
    
    private boolean isvalid(int x, int y, int[][] maze) {
        int m = maze.length;
        int n = maze[0].length;
        return (0 <= x && x < m && 0 <= y && y < n && (maze[x][y] != 1));
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值