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 ...
随机推荐
- Visual Studio 重命名项目名
1. 打开VS Studio,重命名项目 2. 重命名对应的项目文件夹,并重命名项目文件夹下的这两个文件名: 3. 用记事本打开解决方案,修改对应的项目名字和路径 未完 ...... 点击访问原文(进 ...
- Python-06-函数
一.函数的定义 函数是第一类对象,即函数可以当作数据传递 #1 可以被引用 #2 可以当作参数传递 #3 返回值可以是函数 #3 可以当作容器类型的元素 1. 定义方式 def 函数名(参数1,参数2 ...
- WPF矢量字体图标(iconfont)
原文:WPF矢量字体图标(iconfont) 转载:点击打开链接 步骤: 一.下载添加iconfont文件 二.添加到资源文件夹,并设置不复制,且为资源文件 三.增加FIcon.xaml文件 < ...
- Jenkins首次进入的一些设置及配置
1.将Jenkins显示页面修改为中文环境 首先安装中文的插件:在manage Jenkins-Manage Plugins-可选插件 下载完成之后,在系统设置里边,修改为中文格式:manage Je ...
- 基于react-app搭建react-router+redux项目
前言 总括: 本文采用react+redux+react-router+less+es6+webpack,以实现一个简易备忘录(todolist)为例尽可能全面的讲述使用react全家桶实现一个完整应 ...
- Ansible-概念
控住节点 任何装有Ansible的机器.您可以从任何控制节点调用/usr/bin/ansible或来运行命令和剧本/usr/bin/ansible-playbook.您可以将任何安装了Python的计 ...
- MySQL倒序索引测试1
测试环境 MySQL Community Server 准备测试数据 DROP TABLE TB001; CREATE TABLE TB001(ID INT PRIMARY KEY AUTO_INCR ...
- SQL SERVER-查看内存使用情况
--使用内存的各对象 SELECT type, sum(virtual_memory_reserved_kb) as VM_Reserved, sum(virtual_memory_committed ...
- warning警告问题解决1
warning警告问题, 这时可以不去管它, 但如果想解决, 可以这样做: c:\python\lib\site-packages\locust\core.py:17: MonkeyPatchWarn ...
- 为Linux操作系统配置SSH互信
Linux 互信,免登陆 1.切换到要建立互信的用户(以root为例): su - root cd ~ 2.制作密钥并赋权: # ssh-keygen -t dsa #出现 ...