原题链接在这里: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:

  1. There is only one ball and one destination in the maze.
  2. Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
  3. 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.
  4. 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的更多相关文章

  1. [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 ...

  2. [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 ...

  3. 【LeetCode】505. The Maze II 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS 日期 题目地址:https://leetcod ...

  4. 505. The Maze II

    原题链接:https://leetcode.com/articles/the-maze-ii/ 我的思路 在做完了第一道迷宫问题 http://www.cnblogs.com/optor/p/8533 ...

  5. [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 ...

  6. [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 ...

  7. [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 ...

  8. LeetCode 499. The Maze III

    原题链接在这里:https://leetcode.com/problems/the-maze-iii/ 题目: There is a ball in a maze with empty spaces ...

  9. LeetCode 490. The Maze

    原题链接在这里:https://leetcode.com/problems/the-maze/ 题目: There is a ball in a maze with empty spaces and ...

随机推荐

  1. 百度前端技术学院-task1.3源代码

    因为其中有图片,所以就给有图片的位置加了边框和设置了大小,这样哪怕图片不显示也可以知道在哪里. <!DOCTYPE html> <html> <head> < ...

  2. Django ORM 数据库增删改查

    Django ORM 数据库增删改查 增 # 创建.增加数据(推荐) models.UserInfo.objects.create(username=') # 创建.增加数据 dic = {'} mo ...

  3. Windows下非PE方式载荷投递方式研究

    0. 引言 0x1:载荷是什么?在整个入侵过程中起到什么作用? 载荷的作用在整个入侵链路的作用起到纽带的作用,它借助于目标系统提供的某些功能:组件:执行环境,将攻击者的传递的恶意payload包裹起来 ...

  4. 转载 VUE+WebPack环境搭建 https://segmentfault.com/a/1190000010960666

    一.vue有两种使用方式: 1.下载vue.js <script src="vue.js"></script> 2.使用npm npm install vu ...

  5. B树索引最通俗易懂的介绍

    先来一段有莫的对话: 前几天下班回到家后正在处理一个白天没解决的bug,厕所突然传来对象的声音:   对象:xx,你有<时间简史>吗?  我:我去!妹子,你这啥癖好啊,我有时间也不会去捡屎 ...

  6. ASP.NET MVC 允许跨域请求设置

    场景:创建一个图片上传的站点,用于其他站点跨域上传附件和图片之类. 上传插件结合百度的 webuploader.js 经常会碰到,跨域的问题,如下, 处理方式呢,是在web.config 中配置允许跨 ...

  7. 教你玩转Git-合并冲突

    Git 是一个开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目.Git 是 Linus Torvalds 为了帮助管理 Linux 内核开发而开发的一个开放源码的版本控制软件.Git 与 ...

  8. 含有动态未知字段的 JSON 反序列化

    一般来说,正常的 json 长这个模样: { 'Name': 'Bad Boys', 'ReleaseDate': '1995-4-7T00:00:00', 'Genres': [ 'Action', ...

  9. this、对象原型

    this和对象原型 第一章 关于this 1.1 为什么要用this this 提供了一种更优雅的方式来隐式"传递"一个对象引用,因此可以将 API 设计 得更加简洁并且易于复用. ...

  10. 《微信小程序项目开发实战:用WePY、mpvue、Taro打造高效的小程序》(笔记1)WePY开发环境的安装

    WePY的安装或更新都通过npm进行,全局安装或更新WePY命令行工具,使用以下命令: npm install wepy-cli -g 稍等片刻,成功安装后,即可创建WePY项目. 注意:如果npm安 ...