原题链接在这里: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. C++连接SQL

    1.引入ADO#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename( ...

  2. Linux平台上常用到的c语言开发程序

    Linux操作系统上大部分应用程序都是基于C语言开发的.小编将简单介绍Linux平台上常用的C语言开发程序. 一.C程序的结构1.函数 必须有一个且只能有一个主函数main(),主函数的名为main. ...

  3. mosquitto: error while loading shared libraries: libwebsockets.so.12: cannot open shared object file

    错误描述: # mosquitto -c /etc/mosquitto/mosquitto.conf -dmosquitto: error while loading shared libraries ...

  4. java版的状态机实现

    状态机适用场景: C的操作,需要等到A.B的两个操作(A.B顺序操作),那就需要在 A.B之间创建一个状态机(state machine),C的操作需要状态机达到某一个状态才能进行 1. Overvi ...

  5. c++关于IOCP(完成端口)的服务器开发

    本文转载,以便更好的学习C++的服务器开发 1.对IOCP的理解,转载地址 2.在C++中对IOCP的实现,转载地址 注:其实在.net中 ,Socket的服务器开发中,SocketAsyncEven ...

  6. c#高效准确的条形码、线性条码、QR二维码读写类库-SharpBarcode介绍

    SharpBarcode是一款支持.NET(C#,VB)的高效易用的条形码.QR二维码的读取和生成类库. 主要功能: 1.支持几乎所有常见类型的线性条形码和QR二维码的读取,高效读取,准确率高. 2. ...

  7. Git 多人协作 以及推送分支

    参考链接:https://www.liaoxuefeng.com/wiki/896043488029600/900375748016320 当你从远程仓库克隆时,实际上Git自动把本地的仓库的mast ...

  8. node-exporter常用指标含义,比如在prometheus中查询node_load1的指标数据

    参考: https://blog.csdn.net/yjph83/article/details/84909319 https://www.gitbook.com/book/songjiayang/p ...

  9. drf序列化与反序列化

    序列化器-Serializer 定义序列化器 Django REST framework中的Serializer使用类来定义,须继承自rest_framework.serializers.Serial ...

  10. Hibernate 5.x 生成 SessionFactory 源码跟踪分析

    我们要使用 Hibernate 的功能,首先需要读取 Hibernate 的配置文件,根据配置启动 Hibernate ,然后创建 SessionFactory. 创建 SessionFactory ...