美文网首页
499. The Maze III

499. The Maze III

作者: Nancyberry | 来源:发表于2018-05-17 04:37 被阅读0次

Description

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up (u), down (d), left (l) or right(r), but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls on to the hole.

Given the ball position, the hole position and the maze, find out how the ball could drop into the hole by moving the shortest distance. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the hole (included). Output the moving directions by using 'u', 'd', 'l' and 'r'. Since there could be several different shortest ways, you should output the lexicographically smallest way. If the ball cannot reach the hole, output "impossible".

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 ball and the hole coordinates are represented by row and column indexes.

Example 1

Input 1: a maze represented by a 2D array
0 0 0 0 0
1 1 0 0 1
0 0 0 0 0
0 1 0 0 1
0 1 0 0 0

Input 2: ball coordinate (rowBall, colBall) = (4, 3)
Input 3: hole coordinate (rowHole, colHole) = (0, 1)

Output: "lul"
Explanation: There are two shortest ways for the ball to drop into the hole.
The first way is left -> up -> left, represented by "lul".
The second way is up -> left, represented by 'ul'.
Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul".

image.png

Example 2

Input 1: a maze represented by a 2D array
0 0 0 0 0
1 1 0 0 1
0 0 0 0 0
0 1 0 0 1
0 1 0 0 0

Input 2: ball coordinate (rowBall, colBall) = (4, 3)
Input 3: hole coordinate (rowHole, colHole) = (3, 0)
Output: "impossible"
Explanation: The ball cannot reach the hole.

image.png

Note:

  1. There is only one ball and one hole in the maze.
  2. Both the ball and hole 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 the width and the height of the maze won't exceed 30.

Solution

Dijikstra

跟"Maze II"做法很类似,都需要用Dijikstra来解决。不同的是,不仅要将start position加入对立,滑过hole时也要将其加入队列。

还有一个关键点是,要求输出路径最短且字典序最小的path!PriorityQueue排序需要结合dis和path,这个非常重要。

class Solution {
    public static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public static final char[] DIRECTIONS_CHAR = {'u', 'd', 'l', 'r'};
    
    public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
        PriorityQueue<Info> queue 
            = new PriorityQueue<>((a, b) -> 
                                  a.dis != b.dis ?
                                    a.dis - b.dis : a.path.compareTo(b.path));
        queue.offer(new Info(ball[0], ball[1], 0, ""));
        
        while (!queue.isEmpty()) {
            Info info = queue.poll();
            if (info.x == hole[0] && info.y == hole[1]) {   // meet hole
                return info.path;
            }
            
            if (maze[info.x][info.y] == -1) {   // min dis already found for current pos
                continue;
            }
            
            maze[info.x][info.y] = -1;  // mark that min dis found
            
            for (int i = 0; i < DIRECTIONS.length; ++i) {
                int x = info.x;
                int y = info.y;
                int offsetX = DIRECTIONS[i][0];
                int offsetY = DIRECTIONS[i][1];
                int dis = info.dis;
                // move to hole or the next start pos
                while (!(x == hole[0] && y == hole[1])  // tricky
                       && isValid(maze, x + offsetX, y + offsetY) 
                       && maze[x + offsetX][y + offsetY] != 1) {
                    x += offsetX;
                    y += offsetY;
                    ++dis;
                }
                
                queue.offer(new Info(x, y, dis, info.path + DIRECTIONS_CHAR[i]));
            }
        }
        
        return "impossible";
    }
    
    private boolean isValid(int[][] maze, int i, int j) {
        return i >= 0 && i < maze.length && j >= 0 && j < maze[0].length;
    }
    
    class Info {
        int x;
        int y;
        int dis;
        String path;
        
        public Info(int x, int y, int dis, String path) {
            this.x = x;
            this.y = y;
            this.dis = dis;
            this.path = path;
        }
    }
}

相关文章

网友评论

      本文标题:499. The Maze III

      本文链接:https://www.haomeiwen.com/subject/gjyvdftx.html