Nearest Exit from Entrance in Maze (LeetCode 1926): Solution and Explanation
Starting inside a maze of walls and open cells, find the fewest steps to any open cell on the outer border, not counting the entrance itself.
Intuition
Each step moves one cell and costs the same, so the maze is an unweighted graph. The fewest steps to anywhere is exactly what breadth-first search computes.
BFS spreads from the entrance like a wavefront. Everything at distance 1 is discovered before anything at distance 2, and so on. That means the first border cell the wave touches is the nearest exit, and the search can stop right there.
The one trap is the entrance. It may itself sit on the border, but it does not count as an exit. Marking it as visited (or as a wall) before the search starts handles this: the wave never steps back onto it, so it is never reported.
Marking each cell when it is pushed, rather than when it is popped, keeps every cell in the queue at most once and keeps the search linear in the size of the maze.
Approach: Level-by-level BFS from the entrance
- Mark the entrance as
'+'and push it onto a queue. Setsteps = 0. - While the queue is not empty, increase
stepsand process exactly the cells currently in the queue. - For each of the four neighbours of a popped cell, skip it if it is outside the maze or not
'.'. - If the neighbour is on the border, return
steps. - Otherwise mark it as
'+'and push it. - If the queue empties, return
-1.
Step-by-step example
maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
- Mark the entrance (1,2) and put it in the queue.
- steps = 1: pop (1,2). Looking down, (2,2) is a wall. Looking up, (0,2) is open.
- (0,2) is in row 0, so it is on the border and is an exit. Return 1.
- The exit at (1,0) is 2 steps away and (2,3) cannot be reached at all, so 1 is the nearest.
Code: Python, Java, C++
1class Solution:
2 def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
3 m, n = len(maze), len(maze[0])
4 sr, sc = entrance
5 maze[sr][sc] = '+'
6 queue = deque([(sr, sc)])
7 steps = 0
8 while queue:
9 steps += 1
10 for _ in range(len(queue)):
11 r, c = queue.popleft()
12 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
13 nr, nc = r + dr, c + dc
14 if 0 <= nr < m and 0 <= nc < n and maze[nr][nc] == '.':
15 if nr == 0 or nr == m - 1 or nc == 0 or nc == n - 1:
16 return steps
17 maze[nr][nc] = '+'
18 queue.append((nr, nc))
19 return -11class Solution {
2 public int nearestExit(char[][] maze, int[] entrance) {
3 int m = maze.length, n = maze[0].length;
4 maze[entrance[0]][entrance[1]] = '+';
5 Deque<int[]> queue = new ArrayDeque<>();
6 queue.offer(new int[]{entrance[0], entrance[1]});
7 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
8 int steps = 0;
9 while (!queue.isEmpty()) {
10 steps++;
11 for (int size = queue.size(); size > 0; size--) {
12 int[] cur = queue.poll();
13 for (int[] d : dirs) {
14 int nr = cur[0] + d[0], nc = cur[1] + d[1];
15 if (nr < 0 || nr >= m || nc < 0 || nc >= n || maze[nr][nc] != '.') continue;
16 if (nr == 0 || nr == m - 1 || nc == 0 || nc == n - 1) return steps;
17 maze[nr][nc] = '+';
18 queue.offer(new int[]{nr, nc});
19 }
20 }
21 }
22 return -1;
23 }
24}1class Solution {
2public:
3 int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
4 int m = maze.size(), n = maze[0].size();
5 maze[entrance[0]][entrance[1]] = '+';
6 queue<pair<int, int>> q;
7 q.push({entrance[0], entrance[1]});
8 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
9 int steps = 0;
10 while (!q.empty()) {
11 steps++;
12 for (int size = q.size(); size > 0; size--) {
13 auto [r, c] = q.front();
14 q.pop();
15 for (auto& d : dirs) {
16 int nr = r + d[0], nc = c + d[1];
17 if (nr < 0 || nr >= m || nc < 0 || nc >= n || maze[nr][nc] != '.') continue;
18 if (nr == 0 || nr == m - 1 || nc == 0 || nc == n - 1) return steps;
19 maze[nr][nc] = '+';
20 q.push({nr, nc});
21 }
22 }
23 }
24 return -1;
25 }
26};Time and space complexity
O(m * n)
Every open cell is pushed and popped at most once, and each pop looks at four neighbours.
O(m * n)
The queue can hold a large part of the maze in the worst case. Marking visited cells in the maze itself needs no extra array.
Other approaches
BFS with a separate visited array (time O(m * n), space O(m * n))
Keep a boolean grid instead of overwriting the maze. Same complexity, and the input stays unchanged, which some interviewers prefer.
Multi-source BFS from all exits (time O(m * n), space O(m * n))
Start from every open border cell except the entrance and stop when the wave reaches the entrance. Also correct, but it needs an extra pass to collect the exits.
DFS with backtracking (time O(4^(m * n)), space O(m * n))
Explore every path and keep the shortest. Depth-first search does not reach cells in order of distance, so it must try many paths and is exponential in the worst case.
Common mistakes
- Counting the entrance as an exit when it lies on the border. Mark it visited before the search.
- Marking cells as visited when they are popped instead of when they are pushed. The same cell can then be queued several times and the search slows down badly on open mazes.
- Checking the border condition on the popped cell instead of the neighbour, which is off by one step unless the level count is adjusted.
- Forgetting that a maze of a single row or column makes every open cell a border cell.
Frequently asked questions
Why is BFS guaranteed to find the nearest exit?
All moves cost one step, and BFS processes cells in increasing order of distance from the entrance. The first exit it discovers therefore has the smallest distance.
Can I return as soon as I push an exit rather than when I pop it?
Yes. Within a level, every cell being pushed is at the same distance, so the first exit pushed is already a nearest one. Checking on push saves one level of work.
Is it safe to modify the input maze?
On LeetCode, yes. In production code you would usually copy it or use a separate visited array so the caller's data is not changed.