LeetCode 505. The Maze II
原题链接在这里:https://leetcode.com/problems/the-maze-ii/
题目:
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, find the shortest distance for the ball to stop at the destination. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1.
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.
Example 1:
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.

Example 2:
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) = (3, 2) Output: -1 Explanation: There is no way for the ball to stop at the destination.

Note:
- There is only one ball and one destination in the maze.
- Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
- The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
- The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.
题解:
Use PriorityQueue to make sure smaller weight is polling out first.
Mark the current position visited when polling out the node, that means from start to this node, the shortest path has been found.
If polling out node has been marked as visited, then it means other shorter path has visited this node before.
Note: check polled out node has been visited. If not, mark it as visited.
Time Complexity: O(mn*logmn). m = maze.length. n = maze[0].length.
Space: O(mn).
AC Java:
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 [][] visited = new boolean[m][n];
PriorityQueue<int []> minHeap = new PriorityQueue<>((a,b) -> a[2]-b[2]);
minHeap.add(new int[]{start[0], start[1], 0});
while(!minHeap.isEmpty()){
int [] cur = minHeap.poll();
// If smaller value has been found for cur before, skip
if(visited[cur[0]][cur[1]]){
continue;
}
visited[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++;
}
minHeap.add(new int[]{r, c, cur[2]+step});
}
}
return -1;
}
}
Could use LinkedList and a dist array to record the shortest distance from start to this point.
For polled node, go to dist and get the step up to that node, then 4 dirs to the end, accumlated step.
If the new node, dist is -1, or dist > accumlated steps, then update it.
Eventually, return dist[d[0]][d[1]].
Time Complexity: O(mn).
Space:(mn).
Java:
class Solution {
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;
int [][] dist = new int[m][n];
for(int [] arr : dist){
Arrays.fill(arr, -1);
}
LinkedList<int []> que = new LinkedList<>();
que.add(start);
dist[start[0]][start[1]] = 0;
int [][] dirs = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
while(!que.isEmpty()){
int [] cur = que.poll();
for(int [] dir : dirs){
int x = cur[0];
int y = cur[1];
int step = dist[x][y];
while(x + dir[0] >= 0 && x + dir[0] < m && y + dir[1] >= 0 && y + dir[1] < n && maze[x + dir[0]][y + dir[1]] == 0){
x += dir[0];
y += dir[1];
step++;
}
if(dist[x][y] == -1 || dist[x][y] > step){
dist[x][y] = step;
que.add(new int[]{x, y});
}
}
}
return dist[destination[0]][destination[1]];
}
}
类似The Maze.
LeetCode 505. The Maze II的更多相关文章
- [LeetCode] 505. The Maze II 迷宫 II
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] 505. The Maze II 迷宫之二
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- 【LeetCode】505. The Maze II 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS 日期 题目地址:https://leetcod ...
- 505. The Maze II
原题链接:https://leetcode.com/articles/the-maze-ii/ 我的思路 在做完了第一道迷宫问题 http://www.cnblogs.com/optor/p/8533 ...
- [LC] 505. The Maze II
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] 499. The Maze III 迷宫 III
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] 490. The Maze 迷宫
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- LeetCode 499. The Maze III
原题链接在这里:https://leetcode.com/problems/the-maze-iii/ 题目: There is a ball in a maze with empty spaces ...
- LeetCode 490. The Maze
原题链接在这里:https://leetcode.com/problems/the-maze/ 题目: There is a ball in a maze with empty spaces and ...
随机推荐
- 不一样的LCA——luoguP1852跳跳棋
洛谷端题目链接 loj端题目链接 题目大意: 在一条数轴上进行跳跳棋游戏.棋子只能摆在整点上.每个点不能摆超过一个棋子.用跳跳棋完成:棋盘上有3颗棋子,分别在a,b,c这三个位置.我们要通过最少的跳动 ...
- Python中的垃圾回收机制(转)
原文:https://foofish.net/python-gc.html GC作为现代编程语言的自动内存管理机制,专注于两件事:1. 找到内存中无用的垃圾资源 2. 清除这些垃圾并把内存让出来给其他 ...
- git在使用push指令的时候产生的错误
一.问题我们在使用git指令的时候往往会出现如下错误. $ git push -u origin master To https://github.com/pzq7025/ss-fly.git ! [ ...
- Lambda表达式和函数式编程
Lambda表达式和函数式编程 https://www.cnblogs.com/bigbigbigo/p/8422579.html https://www.runoob.com/java/java8- ...
- The underlying connection was closed: An unexpected error occurred on a receive
解决方法 webRequest.KeepAlive = false; ServicePointManager.ServerCertificateValidationCallback += (s, ce ...
- 为什么要用 redis 而不用 map 做缓存?
缓存分为本地缓存和分布式缓存.以 Java 为例,使用自带的 map 或者 guava 实现的是本地缓存,最主要的特点是轻量以及快速,生命周期随着 jvm 的销毁而结束,并且在多实例的情况下,每个实例 ...
- Django--视图函数
目录 视图函数 HttpRequest对象 request属性 request常用方法 HttpResponse对象 render() redirect() JsonResponse 视图函数 一个视 ...
- 8 Traits of an Experienced Programmer that every beginner programmer should know
Referrence: http://whats-online.info/guides-and-info/36/Traits-of-Experienced-Programmer-that-every- ...
- 【转载】 C#中ArrayList集合类的使用
在C#的集合操作过程中,我们一般常用的集合类为List集合,List集合是一种强类型的泛型集合,其实还有一个ArrayList集合类,ArrayList集合类则非泛型类的集合,并且ArrayList集 ...
- 非root安装rpm时,mockbuild does not exist - using root
1.现象 [fedora@k8s-cluster--ycmwlao4q5wz-minion- ~]$ [fedora@k8s-cluster--ycmwlao4q5wz-minion- ~]$ sud ...