Formatted question description: https://leetcode.ca/all/499.html

# 499. The Maze III

## Level

Hard

## 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".
```

**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.
```

**Note:**

- There is only one ball and one hole in the maze.
- Both the ball and hole exist on an empty space, and they will not be at the same position initially.
- 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.
- The maze contains at least 2 empty spaces, and the width and the height of the maze won’t exceed 30.

## Solution

Initialize the distances to `INFINITY`

for all positions except `start`

, which has distance 0. Initialize the paths for all positions to `null`

. Since the shortest distance is required, use priority queue during the search. Starting from `start`

, each time obtain all possible positions the ball can reach and stop at, update the shortest distances and paths for such positions, and then do further search from the new positions. If the ball can reach `hole`

, update the shortest distance and the lexicographically smallest path for `hole`

. After all possible positions are visited, the shortest distances possible and corresponding paths are also obtained. Return the path to reach `hole`

, which is the string of directions if `hole`

can be reached, or “impossible” otherwise.

```
class Solution {
public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
final int WALL = 1;
int rows = maze.length, columns = maze[0].length;
int[][] distances = new int[rows][columns];
String[][] paths = new String[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (maze[i][j] == WALL)
distances[i][j] = -1;
else
distances[i][j] = Integer.MAX_VALUE;
}
}
int shortestDistance = Integer.MAX_VALUE;
String minPath = "impossible";
int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int directionsCount = directions.length;
String[] directionsPath = {"u", "d", "l", "r"};
PriorityQueue<PositionDistancePath> priorityQueue = new PriorityQueue<PositionDistancePath>();
distances[ball[0]][ball[1]] = 0;
paths[ball[0]][ball[1]] = "";
priorityQueue.offer(new PositionDistancePath(ball[0], ball[1], 0, ""));
while (!priorityQueue.isEmpty()) {
PositionDistancePath positionDistancePath = priorityQueue.poll();
int row = positionDistancePath.getRow(), column = positionDistancePath.getColumn(), distance = positionDistancePath.getDistance();
String path = positionDistancePath.getPath();
if (distance > shortestDistance)
break;
for (int i = 0; i < directionsCount; i++) {
int[] direction = directions[i];
int deltaRow = direction[0], deltaColumn = direction[1];
String directionPath = directionsPath[i];
String newPath = path + directionPath;
int moveCount = 0;
int stopRow = row, stopColumn = column;
int curRow = row + deltaRow, curColumn = column + deltaColumn;
while (curRow >= 0 && curRow < rows && curColumn >= 0 && curColumn < columns && maze[curRow][curColumn] != WALL) {
moveCount++;
stopRow = curRow;
stopColumn = curColumn;
if (stopRow == hole[0] && stopColumn == hole[1]) {
int newDistance = distance + moveCount;
if (minPath.equals("impossible") || newDistance < shortestDistance || newDistance == shortestDistance && newPath.compareTo(minPath) < 0) {
distances[hole[0]][hole[1]] = newDistance;
paths[hole[0]][hole[1]] = newPath;
shortestDistance = Math.min(shortestDistance, newDistance);
minPath = newPath;
}
break;
}
curRow = stopRow + deltaRow;
curColumn = stopColumn + deltaColumn;
}
int newDistance = distance + moveCount;
if (newDistance < distances[stopRow][stopColumn] || (newDistance == distances[stopRow][stopColumn] && (paths[stopRow][stopColumn] == null || newPath.compareTo(paths[stopRow][stopColumn]) < 0))) {
distances[stopRow][stopColumn] = newDistance;
paths[stopRow][stopColumn] = newPath;
priorityQueue.offer(new PositionDistancePath(stopRow, stopColumn, newDistance, newPath));
}
}
}
return minPath;
}
}
class PositionDistancePath implements Comparable<PositionDistancePath> {
private int row;
private int column;
private int distance;
private String path = "";
public PositionDistancePath() {
}
public PositionDistancePath(int row, int column, int distance, String path) {
this.row = row;
this.column = column;
this.distance = distance;
this.path = path;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
public int getDistance() {
return distance;
}
public String getPath() {
return path;
}
public int compareTo(PositionDistancePath positionDistance2) {
if (distance != positionDistance2.distance)
return distance - positionDistance2.distance;
return path.compareTo(positionDistance2.path);
}
}
```