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

# 499. The Maze III

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.


Image text

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

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.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][ball] = 0;
paths[ball][ball] = "";
priorityQueue.offer(new PositionDistancePath(ball, ball, 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, deltaColumn = direction;
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 && stopColumn == hole) {
int newDistance = distance + moveCount;
if (minPath.equals("impossible") || newDistance < shortestDistance || newDistance == shortestDistance && newPath.compareTo(minPath) < 0) {
distances[hole][hole] = newDistance;
paths[hole][hole] = 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);
}
}

• // OJ: https://leetcode.com/problems/the-maze-iii/
// Time: O((MN)^2log(MN))
// Space: O((MN)^2)
class Solution {
typedef tuple<int, string, int, int> item; // distance, instruction, x, y
public:
string findShortestWay(vector<vector<int>>& A, vector<int>& ball, vector<int>& hole) {
int M = A.size(), N = A.size(), dirs = { {1,0},{0,-1},{0,1},{-1,0} };
string chars = "dlru";
vector<vector<int>> dist(M, vector<int>(N, INT_MAX));
dist[ball][ball] = 0;
vector<vector<string>> ins(M, vector<string>(N));
priority_queue<item, vector<item>, greater<>> pq;
pq.push({0, "", ball, ball});
while (pq.size()) {
auto [cost, inst, x, y] = pq.top();
pq.pop();
if (x == hole && y == hole) return inst;
if (cost > dist[x][y]) continue;
for (int i = 0; i < 4; ++i) {
auto [dx, dy] = dirs[i];
int a = x + dx, b = y + dy, step = 1;
while (a >= 0 && a < M && b >= 0 && b < N && A[a][b] == 0 && (a != hole || b != hole)) a += dx, b += dy, ++step;
if (a != hole || b != hole) a -= dx, b -= dy, --step;
if (a == x && b == y) continue;
int newCost = cost + step;
auto newInst = inst + chars[i];
if (dist[a][b] > newCost) {
dist[a][b] = newCost;
ins[a][b] = newInst;
pq.push({newCost, newInst, a, b});
} else if (dist[a][b] == newCost && (ins[a][b].empty() || newInst < ins[a][b])) {
ins[a][b] = newInst;
pq.push({newCost, newInst, a, b});
}
}
}
return "impossible";
}
};

• import heapq

class Solution(object):
def findShortestWay(self, maze, ball, hole):
"""
:type maze: List[List[int]]
:type ball: List[int]
:type hole: List[int]
:rtype: str
"""

def next(curr, maze):
height = len(maze)
width = len(maze)
directions = [(-1, 0, "u"), (1, 0, "d"), (0, -1, "l"), (0, 1, "r")]
for di, dj, mark in directions:
dist = 0
i, j = curr
while 0 <= i + di < height and 0 <= j + dj < width and maze[i + di][j + dj] != 1:
i += di
j += dj
dist += 1
if (i, j) == hole:
break
yield (i, j), mark, dist

heap = [(0, "", tuple(ball))]
visited = set()
hole = tuple(hole)
while heap:
dist, word, curr = heapq.heappop(heap)
if curr in visited:
continue
visited |= {curr}
if curr == hole:
return word
for pos, mark, incDist in next(curr, maze):
heapq.heappush(heap, (dist + incDist, word + mark, pos))

return "impossible"