#499
Hard Algorithms The maze iii
Array String Depth-First Search Breadth-First Search Graph Theory Heap (Priority Queue) Matrix Shortest Path
52.3% acceptance
Mar 31, 2026
521
78
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).
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn find_shortest_way(maze: Vec<Vec<i32>>, ball: Vec<i32>, hole: Vec<i32>) -> String {
use std::collections::BinaryHeap;
use std::cmp::Reverse;
let m = maze.len();
let n = maze[0].len();
let (hr, hc) = (hole[0] as usize, hole[1] as usize);
let sr = ball[0] as usize;
let sc = ball[1] as usize;
// dist[r][c] = (minimum_distance, lex_optimal_path).
// Storing one path per cell (not in heap) eliminates O(path_len) String
// cloning per heap push. Heap entries are O(1); lex comparison happens
// only at update time using the current stored path.
let mut dist = vec![vec![(i32::MAX, String::new()); n]; m];
dist[sr][sc] = (0, String::new());
let mut heap: BinaryHeap<Reverse<(i32, usize, usize)>> = BinaryHeap::new();
heap.push(Reverse((0, sr, sc)));
let dirs: [(i32, i32, char); 4] = [(-1, 0, 'u'), (1, 0, 'd'), (0, -1, 'l'), (0, 1, 'r')];
while let Some(Reverse((d, r, c))) = heap.pop() {
if d > dist[r][c].0 {
continue;
}
if r == hr && c == hc {
return dist[r][c].1.clone();
}
for &(dr, dc, ch) in &dirs {
let (mut nr, mut nc) = (r as i32, c as i32);
let mut steps = 0i32;
while nr + dr >= 0 && nr + dr < m as i32 && nc + dc >= 0 && nc + dc < n as i32
&& maze[(nr + dr) as usize][(nc + dc) as usize] == 0
{
nr += dr;
nc += dc;
steps += 1;
if nr as usize == hr && nc as usize == hc {
break;
}
}
let (nr, nc) = (nr as usize, nc as usize);
let new_dist = d + steps;
let cur_dist = dist[nr][nc].0;
if new_dist <= cur_dist {
let mut new_path = dist[r][c].1.clone();
new_path.push(ch);
if new_dist < cur_dist || new_path < dist[nr][nc].1 {
dist[nr][nc] = (new_dist, new_path);
heap.push(Reverse((new_dist, nr, nc)));
}
}
}
}
if dist[hr][hc].0 == i32::MAX {
"impossible".to_string()
} else {
dist[hr][hc].1.clone()
}
}
}