原题链接在这里: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. FusionInsight大数据开发---Oozie应用开发

    Oozie应用开发 要求: 了解Oozie应用开发适用场景 掌握Oozie应用开发 熟悉并使用Oozie常用API Oozie简介 Oozie是一个Hadoop作业的工作流调度管理系统 Oozie工作 ...

  2. 补习系列(17)-springboot mongodb 内嵌数据库【华为云技术分享】

    目录 简介 一.使用 flapdoodle.embed.mongo A. 引入依赖 B. 准备测试类 C. 完善配置 D. 启动测试 细节 二.使用Fongo A. 引入框架 B. 准备测试类 C.业 ...

  3. 【在 Nervos CKB 上做开发】Nervos CKB 脚本编程简介[4]:在 CKB 上实现 WebAssembly

    作者:Xuejie 原文链接:https://xuejie.space/2019_10_09_introduction_to_ckb_script_programming_wasm_on_ckb/ N ...

  4. K8S学习笔记之Pod的Volume emptyDir和hostPath

    0x00 Volume的类型 Volume是Kubernetes Pod中多个容器访问的共享目录. Volume被定义在Pod上,被这个Pod里的多个容器挂在到相同或不同的路径下. Volume的生命 ...

  5. CentOS 7.0 更改SSH 远程连接 端口号

    许多学习过redhat 7的同学们,在使用centos的时候总会遇到一些问题,因为centos在安装时会默认开启一些服务,今天我们就来更改下centos 7.0的SSH端口. 操作步骤: 远程登录到c ...

  6. c# 基本类型存储方式的研究

    基本单位 二进制,当前的计算机系统使用的基本上是二进制系统.二进制的单位是位,每一位可以表示2个数: 0或1.byte(字节) 有8位,可以表示的数为2的8次方,即256个数,范围为[0-255]. ...

  7. 简单聊聊服务发现(redis, zk,etcd, consul)

    什么是服务发现? 服务发现并没有怎样的高深莫测,它的原理再简单不过.只是市面上太多文章将服务发现的难度妖魔化,读者被绕的云里雾里,顿觉自己智商低下不敢高攀. 服务提供者是什么,简单点说就是一个HTTP ...

  8. 【转载】C#中ArrayList集合类使用Add方法添加元素

    ArrayList集合是C#中的一个非泛型的集合类,是弱数据类型的集合类,可以使用ArrayList集合变量来存储集合元素信息,任何数据类型的变量都可加入到同一个ArrayList集合中,因此使用Ar ...

  9. JavaWeb第三天--JavaScript

    JavaScript 1. JavaScript概述 1.1 JavaScript是什么?有什么作用? HTML:就是用来写网页的.(人的身体) CSS:就是用来美化页面的.(人的衣服) JavaSc ...

  10. Qt Graphics-View的打印功能实现

    本文来研究一下Qt Graphics-View的打印功能实现. 在Qt的官方文档中介绍了Graphics-View的打印相关内容. Qt中对打印的支持是有一个独立的printsupport模块来完成的 ...