The Maze III Problem
Description
LeetCode Problem 499.
There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the 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 (must be different from last chosen direction). There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.
Given the m x n maze, the ball's position ball and the hole's position hole, where ball = [ball_row, ball_col] and hole = [hole_row, hole_col], return a string instructions of all the instructions that the ball should follow to drop in the hole with the shortest distance possible. If there are multiple valid instructions, return the lexicographically minimum one. If the ball can't drop in the hole, return "impossible".
If there is a way for the ball to drop in the hole, the answer instructions should contain the characters 'u' (i.e., up), 'd' (i.e., down), 'l' (i.e., left), and 'r' (i.e., right).
The distance is the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included).
You may assume that the borders of the maze are all walls (see examples).
Example 1:

Input: maze = [[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]], ball = [4,3], hole = [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: maze = [[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]], ball = [4,3], hole = [3,0]
Output: "impossible"
Explanation: The ball cannot reach the hole.
Example 3:
Input: maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5]
Output: "dldr"
Constraints:
m == maze.lengthn == maze[i].length1 <= m, n <= 100maze[i][j]is0or1.ball.length == 2hole.length == 20 <= ball_row, hole_row <= m0 <= ball_col, hole_col <= n- Both the ball and the hole exist in an empty space, and they will not be in the same position initially.
- The maze contains at least 2 empty spaces.
Solution
Approach: Dijkstra on (Distance, Path)
This is The Maze II with two twists: the ball stops when it rolls onto the hole, and among the shortest ways we must return the lexicographically smallest instruction string.
The first twist changes the roll: while stepping in a direction, stop as soon as the ball enters the hole, even if there is no wall yet. Every other stop is still right before a wall or the border.
For the second, we run Dijkstra's algorithm on pairs (distance, path) instead of just distances. Pairs are compared by distance first and then by the path string, and the heap pops the smallest pair. For each cell we keep the best pair seen so far, and we only push a new pair when it beats that one. The first time the hole is popped, its pair is the smallest possible: shortest distance, and among those the smallest string. If the heap empties first, return "impossible".
Why keeping just one best pair per cell is enough: suppose two ways reach the same cell with the same distance and paths p < q. Continuing both with the same moves s keeps p + s < q + s, unless p were a prefix of q. That cannot happen, because q would then be p followed by more moves, which all have positive length, so q would be longer. Rolls of length 0 (straight into a wall) are skipped for the same reason.
In Example 1 the hole can be reached by "ul" or "lul", both with distance 6; the pair (6, "lul") is smaller, so it is popped first.
Complexity: O(mn · (max(m, n) + L log(mn))) time, where L is the length of the longest path string: each stopping cell is expanded about once with four rolls of up to max(m, n) steps, and every heap operation compares paths, which costs up to O(L). O(mn · L) space for the stored paths.
import heapq
class Solution:
def findShortestWay(self, maze: List[List[int]], ball: List[int], hole: List[int]) -> str:
m, n = len(maze), len(maze[0])
hr, hc = hole
best = {} # (row, col) -> smallest (distance, path) seen for stopping there
best[(ball[0], ball[1])] = (0, "")
heap = [(0, "", ball[0], ball[1])]
while heap:
d, path, i, j = heapq.heappop(heap)
if (d, path) > best[(i, j)]:
continue # an outdated entry
if (i, j) == (hr, hc):
return path
for a, b, move in ((1, 0, "d"), (0, -1, "l"), (0, 1, "r"), (-1, 0, "u")):
# roll until a wall, the border, or the hole
x, y, steps = i, j, 0
while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0:
x, y, steps = x + a, y + b, steps + 1
if (x, y) == (hr, hc):
break
if steps == 0:
continue
state = (d + steps, path + move)
if (x, y) not in best or state < best[(x, y)]:
best[(x, y)] = state
heapq.heappush(heap, (d + steps, path + move, x, y))
return "impossible"