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));
}
}