Problem

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 = [ballrow, ballcol] and hole = [holerow, holecol], 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).

Examples

Example 1

$$ \Huge \begin{array}{|c|c|c|c|c|c|c|} \hline 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 \\ \hline 🟨 & & 📍 & & & & 🟨 \\ \hline 🟨 & 🟨 & 🟨 & & & 🟨 & 🟨 \\ \hline 🟨 & & & & & & 🟨 \\ \hline 🟨 & & 🟨 & & & 🟨 & 🟨 \\ \hline 🟨 & & 🟨 & & ⚽️ & & 🟨 \\ \hline 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 \\ \hline \end{array} $$

1
2
3
4
5
6
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

$$ \Huge \begin{array}{|c|c|c|c|c|c|c|} \hline 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 \\ \hline 🟨 & & & & & & 🟨 \\ \hline 🟨 & 🟨 & 🟨 & & & 🟨 & 🟨 \\ \hline 🟨 & & & & & & 🟨 \\ \hline 🟨 & 📍 & 🟨 & & & 🟨 & 🟨 \\ \hline 🟨 & & 🟨 & & ⚽️ & & 🟨 \\ \hline 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 \\ \hline \end{array} $$

1
2
3
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

$$ \Huge \begin{array}{|c|c|c|c|c|c|c|c|c|} \hline 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 \\ \hline 🟨 & & & & & ⚽️ & & & 🟨 \\ \hline 🟨 & & & 🟨 & & & 🟨 & & 🟨 \\ \hline 🟨 & & & & & 🟨 & & & 🟨 \\ \hline 🟨 & & & & & & 📍 & 🟨 & 🟨 \\ \hline 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 \\ \hline \end{array} $$

1
2
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"

Solution

Method 1 – Dijkstra’s Algorithm with Lexicographical Path Tracking

Intuition

The key idea is to use Dijkstra’s algorithm to find the shortest path (minimum distance) to the hole, and for equal distances, keep the lexicographically smallest path. For each position, roll the ball in all four directions until it hits a wall or the hole, and track both distance and path string.

Approach

  1. Use a min-heap to always process the cell with the smallest current distance and, for ties, the lexicographically smallest path.
  2. For each cell, roll the ball in all four directions until it hits a wall or the hole, counting the distance and building the path string.
  3. If the new position has a smaller distance or a lexicographically smaller path for the same distance, update and push to the heap.
  4. When the hole is reached, return the path string.
  5. If the hole is unreachable, return “impossible”.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
    public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
        int m = maze.length, n = maze[0].length;
        int[][] dist = new int[m][n];
        String[][] path = new String[m][n];
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                dist[i][j] = Integer.MAX_VALUE;
                path[i][j] = "";
            }
        dist[ball[0]][ball[1]] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
        PriorityQueue<State> heap = new PriorityQueue<>();
        heap.offer(new State(0, "", ball[0], ball[1]));
        int[][] dirs = {{1,0},{0,-1},{0,1},{-1,0}};
        char[] moves = {'d','l','r','u'};
        while (!heap.isEmpty()) {
            State cur = heap.poll();
            int d = cur.dist, i = cur.x, j = cur.y;
            String p = cur.path;
            if (i == hole[0] && j == hole[1]) return p;
            for (int k = 0; k < 4; k++) {
                int x = i, y = j, cnt = 0;
                while (x+dirs[k][0] >= 0 && x+dirs[k][0] < m && y+dirs[k][1] >= 0 && y+dirs[k][1] < n && maze[x+dirs[k][0]][y+dirs[k][1]] == 0) {
                    x += dirs[k][0]; y += dirs[k][1]; cnt++;
                    if (x == hole[0] && y == hole[1]) break;
                }
                String np = p + moves[k];
                if (dist[x][y] > d+cnt || (dist[x][y] == d+cnt && path[x][y].compareTo(np) > 0)) {
                    dist[x][y] = d+cnt;
                    path[x][y] = np;
                    heap.offer(new State(d+cnt, np, x, y));
                }
            }
        }
        return "impossible";
    }
    class State implements Comparable<State> {
        int dist, x, y; String path;
        State(int d, String p, int i, int j) { dist = d; path = p; x = i; y = j; }
        public int compareTo(State o) {
            if (dist != o.dist) return dist - o.dist;
            return path.compareTo(o.path);
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
    def findShortestWay(self, maze: list[list[int]], ball: list[int], hole: list[int]) -> str:
        import heapq
        m, n = len(maze), len(maze[0])
        dirs = [(1,0),(0,-1),(0,1),(-1,0)]
        moves = ['d','l','r','u']
        dist = [[float('inf')] * n for _ in range(m)]
        path = [[''] * n for _ in range(m)]
        dist[ball[0]][ball[1]] = 0
        h = [(0, '', ball[0], ball[1])]
        while h:
            d, p, i, j = heapq.heappop(h)
            if [i, j] == hole:
                return p
            for k, (dx, dy) in enumerate(dirs):
                x, y, cnt = i, j, 0
                while 0 <= x+dx < m and 0 <= y+dy < n and maze[x+dx][y+dy] == 0:
                    x += dx; y += dy; cnt += 1
                    if [x, y] == hole:
                        break
                np = p + moves[k]
                if dist[x][y] > d+cnt or (dist[x][y] == d+cnt and path[x][y] > np):
                    dist[x][y] = d+cnt
                    path[x][y] = np
                    heapq.heappush(h, (d+cnt, np, x, y))
        return "impossible"

Complexity

  • ⏰ Time complexity: O(mn log(mn)), where m and n are the maze dimensions; Dijkstra’s algorithm dominates.
  • 🧺 Space complexity: O(mn), for the distance and path matrices and heap.