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;
}
}
这篇博客介绍了一种不同于普通广度优先搜索(BFS)的算法来解决迷宫中最短路径问题。通过优先队列实现,确保每一步都选择当前最短距离的方向。代码示例展示了如何利用Java实现该算法,当找到目标位置时返回最短步数。

418

被折叠的 条评论
为什么被折叠?



