Problem

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.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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.

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.