#505
Medium Algorithms The maze ii
Array Depth-First Search Breadth-First Search Graph Theory Heap (Priority Queue) Matrix Shortest Path
55.0% acceptance
Mar 31, 2026
1400
63
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).
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn shortest_distance(maze: Vec<Vec<i32>>, start: Vec<i32>, destination: Vec<i32>) -> i32 {
use std::collections::BinaryHeap;
use std::cmp::Reverse;
let m = maze.len();
let n = maze[0].len();
let (dr, dc) = (destination[0] as usize, destination[1] as usize);
let mut dist = vec![vec![i32::MAX; n]; m];
let sr = start[0] as usize;
let sc = start[1] as usize;
dist[sr][sc] = 0;
let mut heap = BinaryHeap::new();
heap.push(Reverse((0i32, sr, sc)));
let dirs: [(i32, i32); 4] = [(-1,0),(1,0),(0,-1),(0,1)];
while let Some(Reverse((d, r, c))) = heap.pop() {
if d > dist[r][c] { continue; }
if r == dr && c == dc { return d; }
for &(ddr, ddc) in &dirs {
let (mut nr, mut nc) = (r as i32, c as i32);
let mut steps = 0;
while nr + ddr >= 0 && nr + ddr < m as i32 && nc + ddc >= 0 && nc + ddc < n as i32 && maze[(nr + ddr) as usize][(nc + ddc) as usize] == 0 {
nr += ddr;
nc += ddc;
steps += 1;
}
let (nr, nc) = (nr as usize, nc as usize);
let new_dist = d + steps;
if new_dist < dist[nr][nc] {
dist[nr][nc] = new_dist;
heap.push(Reverse((new_dist, nr, nc)));
}
}
}
-1
}
}