#490
Medium Algorithms The maze
Array Depth-First Search Breadth-First Search Matrix
60.4% acceptance
Mar 31, 2026
1930
199
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 true if the ball can stop at the destination, otherwise return false.
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 has_path(maze: Vec<Vec<i32>>, start: Vec<i32>, destination: Vec<i32>) -> bool {
use std::collections::VecDeque;
let m = maze.len();
let n = maze[0].len();
let (sr, sc) = (start[0] as usize, start[1] as usize);
let (dr, dc) = (destination[0] as usize, destination[1] as usize);
let mut visited = vec![vec![false; n]; m];
visited[sr][sc] = true;
let mut queue = VecDeque::new();
queue.push_back((sr, sc));
let dirs: [(i32, i32); 4] = [(-1,0),(1,0),(0,-1),(0,1)];
while let Some((r, c)) = queue.pop_front() {
if r == dr && c == dc { return true; }
for &(dr2, dc2) in &dirs {
let (mut nr, mut nc) = (r as i32, c as i32);
while nr + dr2 >= 0 && nr + dr2 < m as i32 && nc + dc2 >= 0 && nc + dc2 < n as i32 && maze[(nr + dr2) as usize][(nc + dc2) as usize] == 0 {
nr += dr2;
nc += dc2;
}
let (nr, nc) = (nr as usize, nc as usize);
if !visited[nr][nc] {
visited[nr][nc] = true;
queue.push_back((nr, nc));
}
}
}
false
}
}