Problem

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling updownleft or right, but it won’t stop rolling until hitting a wall. When the ball stops, it could choose the next direction.

Given the ball’s start position, the destination and the maze, find the shortest distance for the ball to stop at the destination. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1.

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 start and destination coordinates are represented by row and column indexes.

1.There is only one ball and one destination in the maze. 2.Both the ball and the destination 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 both the width and height of the maze won’t exceed 100.

Examples

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

	Input:  
	(rowStart, colStart) = (0,4)
	(rowDest, colDest)= (4,4)
	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

	Output:  12
	
	Explanation:
	(0,4)->(0,3)->(1,3)->(1,2)->(1,1)->(1,0)->(2,0)->(2,1)->(2,2)->(3,2)->(4,2)->(4,3)->(4,4)

Example 2:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15

	Input:
	(rowStart, colStart) = (0,4)
	(rowDest, colDest)= (0,0)
	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

	Output:  6
	
	Explanation:
	(0,4)->(0,3)->(1,3)->(1,2)->(1,1)->(1,0)->(0,0)
	

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.