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

  1. Input 1: a maze represented by a 2D array
  2.  
  3. 0 0 1 0 0
  4. 0 0 0 0 0
  5. 0 0 0 1 0
  6. 1 1 0 1 1
  7. 0 0 0 0 0
  8.  
  9. Input 2: start coordinate (rowStart, colStart) = (0, 4)
  10. Input 3: destination coordinate (rowDest, colDest) = (4, 4)
  11.  
  12. Output: 12
  13.  
  14. Explanation: One shortest way is : left -> down -> left -> down -> right -> down -> right.
  15. The total distance is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.

Example 2:

  1. Input 1: a maze represented by a 2D array
  2.  
  3. 0 0 1 0 0
  4. 0 0 0 0 0
  5. 0 0 0 1 0
  6. 1 1 0 1 1
  7. 0 0 0 0 0
  8.  
  9. Input 2: start coordinate (rowStart, colStart) = (0, 4)
  10. Input 3: destination coordinate (rowDest, colDest) = (3, 2)
  11.  
  12. Output: -1
  13.  
  14. 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:

  1. class Solution {
  2. int [][] dirs = new int[][]{{-1,0}, {1,0}, {0,-1}, {0,1}};
  3.  
  4. public int shortestDistance(int[][] maze, int[] start, int[] destination) {
  5. if(maze == null || maze.length == 0 || maze[0].length == 0){
  6. return -1;
  7. }
  8.  
  9. int m = maze.length;
  10. int n = maze[0].length;
  11. boolean [][] visited = new boolean[m][n];
  12. PriorityQueue<int []> minHeap = new PriorityQueue<>((a,b) -> a[2]-b[2]);
  13. minHeap.add(new int[]{start[0], start[1], 0});
  14. while(!minHeap.isEmpty()){
  15. int [] cur = minHeap.poll();
  16.  
  17. // If smaller value has been found for cur before, skip
  18. if(visited[cur[0]][cur[1]]){
  19. continue;
  20. }
  21.  
  22. visited[cur[0]][cur[1]] = true;
  23. if(cur[0] == destination[0] && cur[1] == destination[1]){
  24. return cur[2];
  25. }
  26.  
  27. for(int [] dir : dirs){
  28. int r = cur[0];
  29. int c = cur[1];
  30. int step = 0;
  31. 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){
  32. r += dir[0];
  33. c += dir[1];
  34. step++;
  35. }
  36.  
  37. minHeap.add(new int[]{r, c, cur[2]+step});
  38. }
  39. }
  40.  
  41. return -1;
  42. }
  43. }

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:

  1. class Solution {
  2. public int shortestDistance(int[][] maze, int[] start, int[] destination) {
  3. if(maze == null || maze.length == 0 || maze[0].length == 0){
  4. return -1;
  5. }
  6.  
  7. int m = maze.length;
  8. int n = maze[0].length;
  9. int [][] dist = new int[m][n];
  10. for(int [] arr : dist){
  11. Arrays.fill(arr, -1);
  12. }
  13.  
  14. LinkedList<int []> que = new LinkedList<>();
  15. que.add(start);
  16. dist[start[0]][start[1]] = 0;
  17. int [][] dirs = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
  18.  
  19. while(!que.isEmpty()){
  20. int [] cur = que.poll();
  21. for(int [] dir : dirs){
  22. int x = cur[0];
  23. int y = cur[1];
  24. int step = dist[x][y];
  25. 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){
  26. x += dir[0];
  27. y += dir[1];
  28. step++;
  29. }
  30.  
  31. if(dist[x][y] == -1 || dist[x][y] > step){
  32. dist[x][y] = step;
  33. que.add(new int[]{x, y});
  34. }
  35. }
  36. }
  37.  
  38. return dist[destination[0]][destination[1]];
  39. }
  40. }

类似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. centos 7 重新设置分区大小

    一.基础概念Cent0S 7默认启用LVM2(Logical Volume Manager),把机器的一块硬盘分为两个区sda1和sda2,其中分区sda1作为系统盘/boot挂载,少量空间:sda2 ...

  2. nginx location指令详解

    Nginx的HTTP配置主要包括三个区块,结构如下: http { //这个是协议级别 include mime.types; default_type application/octet-strea ...

  3. Prometheus 配置采集目标

    Prometheus 配置采集目标 1.根据配置的任务(job)以http/s周期性的收刮(scrape/pull)2.指定目标(target)上的指标(metric).目标(target)3.可以以 ...

  4. Python做一个计时器的动画

    一.问题在做连连看的时候需要加一个计时器的动画,这样就完成了计时功能的设计. 二.解决主要思路: 1.先产生一个画布,用深颜色填充满. 2.产生一个新的矩阵用来覆盖画布,背景用白色,就可以渲染出来递减 ...

  5. Shell学习笔记之关于 >/dev/null 2>&1 详解

    shell中可能经常能看到:>/dev/null 2>&1 命令的结果可以通过%>的形式来定义输出 分解这个组合:“>/dev/null 2>&1” 为五 ...

  6. SAP销售订单需求类型的确定优秀级

    需求类型的确定优秀级:1.策略组里的需求类型:2.MRP组里的:3.SO行项目类别+MRP类型4.SO行项目类别 部分截图:

  7. 备忘】HttpContextAccessor类

    AspNetCore / src / Http / Http / src / HttpContextAccessor.cs // Copyright (c) .NET Foundation. All ...

  8. IIS 图片 JS CSS 500错误

    1.检查站点MIME类型是否可以正常加载

  9. Java的Annnotation (注解)

    注解是什么呢? 其实就像商场的商品上都贴有自己的标签一样,它提供了关于这个商品的许多额外信息.你可以根据这些信息对其进行附加的处理. (Java的语法糖果然比较差劲), 这个name()方法太累赘了, ...

  10. Java自学-接口与继承 隐藏

    Java中的方法隐藏 与重写类似,方法的重写是子类覆盖父类的对象方法 隐藏,就是子类覆盖父类的类方法 步骤 1 : 父类 父类有一个类方法 :battleWin package charactor; ...