#1926
Medium Algorithms Nearest exit from entrance in maze
Array Breadth-First Search Matrix
48.3% acceptance
Feb 25, 2026
2620
126
You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
Solution
Rust
Time O(n * m)
Space O(n * m)
use std::collections::VecDeque;
impl Solution {
pub fn nearest_exit(maze: Vec<Vec<char>>, entrance: Vec<i32>) -> i32 {
let m = maze.len();
let n = maze[0].len();
let mut visited = vec![vec![false; n]; m];
let mut queue = VecDeque::new();
let (sr, sc) = (entrance[0] as usize, entrance[1] as usize);
visited[sr][sc] = true;
queue.push_back((sr, sc, 0));
let dirs = [(0i32, 1i32), (0, -1), (1, 0), (-1, 0)];
while let Some((r, c, dist)) = queue.pop_front() {
for &(dr, dc) in &dirs {
let nr = r as i32 + dr;
let nc = c as i32 + dc;
if nr < 0 || nr >= m as i32 || nc < 0 || nc >= n as i32 {
continue;
}
let (nr, nc) = (nr as usize, nc as usize);
if visited[nr][nc] || maze[nr][nc] == '+' {
continue;
}
if nr == 0 || nr == m - 1 || nc == 0 || nc == n - 1 {
return dist + 1;
}
visited[nr][nc] = true;
queue.push_back((nr, nc, dist + 1));
}
}
-1
}
}