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.

Given the m x n maze, the ball’s start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return the shortest distance for the ball to stop at the destination. If the ball cannot stop at destination, return -1.

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|} \hline 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 \\ \hline 🟨 & & & 🟨 & \color{green} \triangleleft & ⚽️ & 🟨 \\ \hline 🟨 & & & \color{green} \triangleleft & \color{green} \triangledown & & 🟨 \\ \hline 🟨 & & & \color{green} \triangledown & 🟨 & & 🟨 \\ \hline 🟨 & 🟨 & 🟨 & \color{green} \triangledown & 🟨 & 🟨 & 🟨 \\ \hline 🟨 & & & \color{green} \triangledown & \color{green} \triangleright & 📍 & 🟨 \\ \hline 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 & 🟨 \\ \hline \end{array} $$

1
2
3
4
Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
Output: 12
Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.
The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. Note that ehy have counted the number of stops (including direction changes) instead of counting every cell travelled.

Example 2

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

1
2
3
Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
Output: -1
Explanation: There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.

Example 3

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

1
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]], start = [4,3], destination = [0,1]
Output: -1

Solution

Method 1 – Dijkstra’s Algorithm

Intuition

The key idea is to use Dijkstra’s algorithm to always expand the path with the minimum distance so far. For each position, roll the ball in all four directions until it hits a wall, and if the new distance is less than the previously recorded distance, update and push to the heap.

Approach

  1. Use a min-heap to always process the cell with the smallest current distance.
  2. For each cell, roll the ball in all four directions until it hits a wall, counting the distance.
  3. If the new position has a smaller distance than previously recorded, update and push to the heap.
  4. When the destination is reached, return the distance.
  5. If the destination is unreachable, return -1.

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
class Solution {
public:
    int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& dest) {
        int m = maze.size(), n = maze[0].size();
        vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
        dist[start[0]][start[1]] = 0;
        priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;
        pq.emplace(0, start[0], start[1]);
        int dirs[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
        while (!pq.empty()) {
            auto [d, i, j] = pq.top(); pq.pop();
            if (i == dest[0] && j == dest[1]) return d;
            for (auto& dir : dirs) {
                int x = i, y = j, cnt = 0;
                while (x+dir[0] >= 0 && x+dir[0] < m && y+dir[1] >= 0 && y+dir[1] < n && maze[x+dir[0]][y+dir[1]] == 0) {
                    x += dir[0]; y += dir[1]; cnt++;
                }
                if (dist[x][y] > d + cnt) {
                    dist[x][y] = d + cnt;
                    pq.emplace(dist[x][y], x, y);
                }
            }
        }
        return -1;
    }
};
 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
func shortestDistance(maze [][]int, start []int, dest []int) int {
    m, n := len(maze), len(maze[0])
    dist := make([][]int, m)
    for i := range dist {
        dist[i] = make([]int, n)
        for j := range dist[i] {
            dist[i][j] = 1<<31 - 1
        }
    }
    dist[start[0]][start[1]] = 0
    pq := &hp{}
    heap.Init(pq)
    heap.Push(pq, [3]int{0, start[0], start[1]})
    dirs := [][2]int{{0,1},{1,0},{0,-1},{-1,0}}
    for pq.Len() > 0 {
        d, i, j := (*pq)[0][0], (*pq)[0][1], (*pq)[0][2]
        heap.Pop(pq)
        if i == dest[0] && j == dest[1] {
            return d
        }
        for _, dir := range dirs {
            x, y, cnt := i, j, 0
            for x+dir[0] >= 0 && x+dir[0] < m && y+dir[1] >= 0 && y+dir[1] < n && maze[x+dir[0]][y+dir[1]] == 0 {
                x += dir[0]; y += dir[1]; cnt++
            }
            if dist[x][y] > d+cnt {
                dist[x][y] = d+cnt
                heap.Push(pq, [3]int{dist[x][y], x, y})
            }
        }
    }
    return -1
}
type hp [][3]int
func (h hp) Len() int           { return len(h) }
func (h hp) Less(i, j int) bool { return h[i][0] < h[j][0] }
func (h hp) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(x interface{}) { *h = append(*h, x.([3]int)) }
func (h *hp) Pop() interface{}   { old := *h; x := old[len(old)-1]; *h = old[:len(old)-1]; return x }
 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
class Solution {
    public int shortestDistance(int[][] maze, int[] start, int[] dest) {
        int m = maze.length, n = maze[0].length;
        int[][] dist = new int[m][n];
        for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
        dist[start[0]][start[1]] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
        pq.offer(new int[]{0, start[0], start[1]});
        int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
        while (!pq.isEmpty()) {
            int[] cur = pq.poll();
            int d = cur[0], i = cur[1], j = cur[2];
            if (i == dest[0] && j == dest[1]) return d;
            for (int[] dir : dirs) {
                int x = i, y = j, cnt = 0;
                while (x+dir[0] >= 0 && x+dir[0] < m && y+dir[1] >= 0 && y+dir[1] < n && maze[x+dir[0]][y+dir[1]] == 0) {
                    x += dir[0]; y += dir[1]; cnt++;
                }
                if (dist[x][y] > d + cnt) {
                    dist[x][y] = d + cnt;
                    pq.offer(new int[]{dist[x][y], x, y});
                }
            }
        }
        return -1;
    }
}
 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 {
    fun shortestDistance(maze: Array<IntArray>, start: IntArray, dest: IntArray): Int {
        val m = maze.size
        val n = maze[0].size
        val dist = Array(m) { IntArray(n) { Int.MAX_VALUE } }
        dist[start[0]][start[1]] = 0
        val pq = java.util.PriorityQueue(compareBy<IntArray> { it[0] })
        pq.add(intArrayOf(0, start[0], start[1]))
        val dirs = arrayOf(0 to 1, 1 to 0, 0 to -1, -1 to 0)
        while (pq.isNotEmpty()) {
            val (d, i, j) = pq.remove()
            if (i == dest[0] && j == dest[1]) return d
            for ((dx, dy) in dirs) {
                var x = i; var y = j; var cnt = 0
                while (x+dx in 0 until m && y+dy in 0 until n && maze[x+dx][y+dy] == 0) {
                    x += dx; y += dy; cnt++
                }
                if (dist[x][y] > d + cnt) {
                    dist[x][y] = d + cnt
                    pq.add(intArrayOf(dist[x][y], x, y))
                }
            }
        }
        return -1
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def shortestDistance(self, maze: list[list[int]], start: list[int], dest: list[int]) -> int:
        import heapq
        m, n = len(maze), len(maze[0])
        dist = [[float('inf')] * n for _ in range(m)]
        dist[start[0]][start[1]] = 0
        h = [(0, start[0], start[1])]
        while h:
            d, i, j = heapq.heappop(h)
            if [i, j] == dest:
                return d
            for dx, dy in ((0,1),(1,0),(0,-1),(-1,0)):
                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 dist[x][y] > d + cnt:
                    dist[x][y] = d + cnt
                    heapq.heappush(h, (dist[x][y], x, y))
        return -1
 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
impl Solution {
    pub fn shortest_distance(maze: Vec<Vec<i32>>, start: Vec<i32>, dest: Vec<i32>) -> i32 {
        use std::collections::BinaryHeap;
        let m = maze.len();
        let n = maze[0].len();
        let mut dist = vec![vec![i32::MAX; n]; m];
        dist[start[0] as usize][start[1] as usize] = 0;
        let mut h = BinaryHeap::new();
        h.push((0, start[0] as usize, start[1] as usize));
        let dirs = [(0,1),(1,0),(0,-1),(-1,0)];
        while let Some((d, i, j)) = h.pop() {
            let d = -d;
            if i == dest[0] as usize && j == dest[1] as usize { return d; }
            for (dx, dy) in dirs.iter() {
                let mut x = i as i32;
                let mut y = j as i32;
                let mut cnt = 0;
                while x+dx >= 0 && x+dx < m as i32 && y+dy >= 0 && y+dy < n as i32 && maze[(x+dx) as usize][(y+dy) as usize] == 0 {
                    x += dx; y += dy; cnt += 1;
                }
                let (x, y) = (x as usize, y as usize);
                if dist[x][y] > d + cnt {
                    dist[x][y] = d + cnt;
                    h.push((-(dist[x][y]), x, y));
                }
            }
        }
        -1
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    shortestDistance(maze: number[][], start: number[], dest: number[]): number {
        const m = maze.length, n = maze[0].length;
        const dist = Array.from({length: m}, () => Array(n).fill(Infinity));
        dist[start[0]][start[1]] = 0;
        const h: [number, number, number][] = [[0, start[0], start[1]]];
        while (h.length) {
            h.sort((a, b) => a[0] - b[0]);
            const [d, i, j] = h.shift()!;
            if (i === dest[0] && j === dest[1]) return d;
            for (const [dx, dy] of [[0,1],[1,0],[0,-1],[-1,0]]) {
                let x = i, y = j, cnt = 0;
                while (x+dx >= 0 && x+dx < m && y+dy >= 0 && y+dy < n && maze[x+dx][y+dy] === 0) {
                    x += dx; y += dy; cnt++;
                }
                if (dist[x][y] > d + cnt) {
                    dist[x][y] = d + cnt;
                    h.push([dist[x][y], x, y]);
                }
            }
        }
        return -1;
    }
}

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 matrix and heap.

Method 2 – BFS on an expanded state (direction-aware)

Intuition

Dijkstra is the most natural choice because edge weights (the number of cells rolled between stopping points) vary. However, you can convert the problem into a unit-weight graph by expanding the state to include the current moving direction. If you simulate the ball’s motion one empty cell at a time and treat each step as weight 1, a plain BFS finds the shortest number of cell-steps needed to reach a stopping state at the destination. The trick is to only allow direction changes when the ball is stopped (i.e., the next cell in the current direction is a wall).

This produces a state-space of size O(m * n * 4) (4 directions per cell). Each transition either moves the ball one cell forward in the same direction (cost 1) or — when blocked — switches direction at the same cell (cost 0). Representing turning as a zero-cost transition still works with BFS because we enqueue turn states without increasing distance (we don’t need 0-1 BFS here because turns can be processed immediately without enqueuing extra distance). In practice the algorithm uses a deque/queue and marks visited (x,y,dir) to avoid revisits.

Approach

  1. Model states as (x, y, dir) where dir is one of the four directions the ball will next attempt to roll.
  2. Initialize the queue with the start cell and all 4 directions (distance 0). If the start is already the destination and it’s a stopping cell (at least one direction immediately blocked), return 0.
  3. While the queue is not empty, pop a state. If the next cell in the current direction is empty, step forward to (x+dx, y+dy, dir) with distance+1. If the next cell is a wall, the ball is stopped at (x, y): if (x, y) == destination, return the current distance; otherwise enqueue the same cell with all other directions (turns) at the same distance (if not visited).
  4. If the BFS completes without finding a stopping state at destination, return -1.

This BFS simulates the ball moving one cell at a time, so distances are exactly the number of empty spaces traversed and the first time we reach a stopping state at destination is the shortest distance.

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
class Solution {
public:
    int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& dest) {
        int m = maze.size(), n = maze[0].size();
        if (start == dest) {
            // If start==dest and it's already a stopping cell, distance is 0.
            for (auto &d : vector<pair<int,int>>{{0,1},{1,0},{0,-1},{-1,0}}) {
                int nx = start[0] + d.first, ny = start[1] + d.second;
                if (nx < 0 || nx >= m || ny < 0 || ny >= n || maze[nx][ny] == 1) return 0;
            }
        }
        int dirs[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
        // visited[x][y][dir]
        vector<vector<array<bool,4>>> vis(m, vector<array<bool,4>>(n));
        deque<tuple<int,int,int,int>> q; // x,y,dir,dist
        for (int di = 0; di < 4; ++di) {
            vis[start[0]][start[1]][di] = true;
            q.emplace_back(start[0], start[1], di, 0);
        }
        while (!q.empty()) {
            auto [x,y,di,dist] = q.front(); q.pop_front();
            int dx = dirs[di][0], dy = dirs[di][1];
            int nx = x + dx, ny = y + dy;
            if (nx >= 0 && nx < m && ny >= 0 && ny < n && maze[nx][ny] == 0) {
                // Move one step forward in the same direction
                if (!vis[nx][ny][di]) {
                    vis[nx][ny][di] = true;
                    q.emplace_back(nx, ny, di, dist + 1);
                }
            } else {
                // We are stopped at (x,y)
                if (x == dest[0] && y == dest[1]) return dist;
                // Try turning to other directions (cost 0)
                for (int ndi = 0; ndi < 4; ++ndi) {
                    if (ndi == di) continue;
                    if (!vis[x][y][ndi]) {
                        vis[x][y][ndi] = true;
                        q.emplace_back(x, y, ndi, dist);
                    }
                }
            }
        }
        return -1;
    }
};
 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
from collections import deque

class Solution:
    def shortestDistance(self, maze: list[list[int]], start: list[int], dest: list[int]) -> int:
        m, n = len(maze), len(maze[0])
        sx, sy = start
        dxs = [(0,1),(1,0),(0,-1),(-1,0)]
        # Quick check: start == dest and stoppable
        if start == dest:
            for dx, dy in dxs:
                nx, ny = sx + dx, sy + dy
                if nx < 0 or nx >= m or ny < 0 or ny >= n or maze[nx][ny] == 1:
                    return 0
        # visited[x][y][dir]
        visited = [[[False]*4 for _ in range(n)] for __ in range(m)]
        q = deque()
        for di in range(4):
            visited[sx][sy][di] = True
            q.append((sx, sy, di, 0))
        while q:
            x, y, di, dist = q.popleft()
            dx, dy = dxs[di]
            nx, ny = x + dx, y + dy
            if 0 <= nx < m and 0 <= ny < n and maze[nx][ny] == 0:
                if not visited[nx][ny][di]:
                    visited[nx][ny][di] = True
                    q.append((nx, ny, di, dist + 1))
            else:
                # stopped at (x, y)
                if [x, y] == dest:
                    return dist
                for ndi in range(4):
                    if ndi == di: continue
                    if not visited[x][y][ndi]:
                        visited[x][y][ndi] = True
                        q.append((x, y, ndi, dist))
        return -1

Complexity

  • ⏰ Time complexity: O(m * n) – there are O(m * n * 4) states (4 directions per cell) and each state is processed at most once; each transition is O(1), so overall O(m * n).
  • 🧺 Space complexity: O(m * n) – visited/state bookkeeping requires O(m * n * 4) bits/booleans which is O(m * n).