Home
DSA Patterns
Breadth-First Search
Nearest Exit from Entrance in Maze
Nearest Exit from Entrance in Maze (LeetCode 1926)
Nearest Exit from Entrance in Maze (LeetCode 1926): find the fewest steps from the entrance to any empty cell on the border of a maze, not counting the entrance itself. BFS from the entrance reaches cells in order of distance, so the first border cell it finds is the answer.
Problem Understanding
Nearest Exit from Entrance in Maze (LeetCode 1926): maze is a grid of empty cells "." and walls "+", and entrance = [row, col] is an empty cell. You may move up, down, left or right into empty cells. An exit is an empty cell on the border of the maze; the entrance does not count. Return the number of steps on the shortest path to the nearest exit, or -1 if there is none.
Examples: [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance [1,2] → 1; [["+","+","+"],[".",".","."],["+","+","+"]], entrance [1,0] → 2; [[".","+"]], entrance [0,0] → -1.
The Intuition: Shortest Path in an Unweighted Grid Is BFS
Each move costs the same, so the shortest path is the one BFS finds: it spreads out from the entrance one ring of cells at a time.
- Mark the entrance as visited (a wall), since it is never an exit, and queue it with distance 0.
- Dequeue a cell and try its four neighbours. Skip anything off the grid, a wall or already visited.
- An empty neighbour on the border is the nearest exit: return the current distance + 1.
- Otherwise mark it and queue it with distance + 1.
- If the queue empties, no exit is reachable: return -1.
It is the same grid BFS as Rotting Oranges and 01 Matrix, from a single source and stopping early.
Nearest Exit from Entrance in Maze Visualization
+ = WALL · . = EMPTY · NUMBER = STEPS FROM THE ENTRANCE
ENTRANCE IS NOT AN EXIT
distance
:
Answer
:
queue (front first)
Mark the entrance (1, 2) as a wall, since it is never an exit, and queue it at distance 0
Next
Dequeue (1, 2), 0 steps from the entrance
maze
row
col
Walls are dark and empty cells pale. Once BFS queues a cell it shows its distance from the entrance, and the arrow points at the neighbour being tried. Try Example 2, where the entrance is on the border but does not count, and Winding, where the path turns before it reaches the edge.
Nearest Exit from Entrance in Maze Dry Run
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2].
| Step | Cell | Neighbour tried | Result |
|---|---|---|---|
| 1 | (1, 2), distance 0 | (2, 2) below | a wall: skip |
| 2 | (1, 2), distance 0 | (0, 2) above | empty and on the border: exit |
The entrance was marked as a wall first, so it is never counted as an exit.
Answer: 1.
Nearest Exit from Entrance in Maze LeetCode Solution
A queue of (row, column, distance), cells marked when queued, and a border check on every new empty cell.
Nearest Exit from Entrance in Maze Code
1var nearestExit = function(maze, entrance) {2 const rows = maze.length, cols = maze[0].length;3 const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];4 maze[entrance[0]][entrance[1]] = '+';5 const queue = [[entrance[0], entrance[1], 0]];6 for (let head = 0; head < queue.length; head++) {7 const [r, c, steps] = queue[head];8 for (const [dr, dc] of dirs) {9 const nr = r + dr, nc = c + dc;10 if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && maze[nr][nc] === '.') {11 if (nr === 0 || nr === rows - 1 || nc === 0 || nc === cols - 1) {12 return steps + 1;13 }14 maze[nr][nc] = '+';15 queue.push([nr, nc, steps + 1]);16 }17 }18 }19 return -1;20};
Nearest Exit from Entrance in Maze in Python, Java, C++, TypeScript and C
Nearest Exit from Entrance in Maze in Python
class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
rows, cols = len(maze), len(maze[0])
r0, c0 = entrance
maze[r0][c0] = "+"
queue = deque([(r0, c0, 0)])
while queue:
r, c, steps = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and maze[nr][nc] == ".":
if nr == 0 or nr == rows - 1 or nc == 0 or nc == cols - 1:
return steps + 1
maze[nr][nc] = "+"
queue.append((nr, nc, steps + 1))
return -1Nearest Exit from Entrance in Maze in Java
class Solution {
public int nearestExit(char[][] maze, int[] entrance) {
int rows = maze.length, cols = maze[0].length;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
maze[entrance[0]][entrance[1]] = '+';
Deque<int[]> queue = new ArrayDeque<>();
queue.offer(new int[]{entrance[0], entrance[1], 0});
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && maze[nr][nc] == '.') {
if (nr == 0 || nr == rows - 1 || nc == 0 || nc == cols - 1) {
return cur[2] + 1;
}
maze[nr][nc] = '+';
queue.offer(new int[]{nr, nc, cur[2] + 1});
}
}
}
return -1;
}
}Nearest Exit from Entrance in Maze in C++
class Solution {
public:
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
int rows = maze.size(), cols = maze[0].size();
int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
maze[entrance[0]][entrance[1]] = '+';
queue<array<int, 3>> q;
q.push({entrance[0], entrance[1], 0});
while (!q.empty()) {
auto [r, c, steps] = q.front();
q.pop();
for (auto& d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && maze[nr][nc] == '.') {
if (nr == 0 || nr == rows - 1 || nc == 0 || nc == cols - 1) {
return steps + 1;
}
maze[nr][nc] = '+';
q.push({nr, nc, steps + 1});
}
}
}
return -1;
}
};Nearest Exit from Entrance in Maze in TypeScript
function nearestExit(maze: string[][], entrance: number[]): number {
const rows = maze.length, cols = maze[0].length;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
maze[entrance[0]][entrance[1]] = '+';
const queue: number[][] = [[entrance[0], entrance[1], 0]];
for (let head = 0; head < queue.length; head++) {
const [r, c, steps] = queue[head];
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && maze[nr][nc] === '.') {
if (nr === 0 || nr === rows - 1 || nc === 0 || nc === cols - 1) {
return steps + 1;
}
maze[nr][nc] = '+';
queue.push([nr, nc, steps + 1]);
}
}
}
return -1;
}Nearest Exit from Entrance in Maze in C
int nearestExit(char** maze, int mazeSize, int* mazeColSize, int* entrance, int entranceSize) {
int rows = mazeSize, cols = mazeColSize[0];
int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int* qr = malloc(rows * cols * sizeof(int));
int* qc = malloc(rows * cols * sizeof(int));
int* qd = malloc(rows * cols * sizeof(int));
int head = 0, tail = 0, answer = -1;
maze[entrance[0]][entrance[1]] = '+';
qr[tail] = entrance[0]; qc[tail] = entrance[1]; qd[tail++] = 0;
while (head < tail && answer == -1) {
int r = qr[head], c = qc[head], steps = qd[head++];
for (int k = 0; k < 4 && answer == -1; k++) {
int nr = r + dirs[k][0], nc = c + dirs[k][1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && maze[nr][nc] == '.') {
if (nr == 0 || nr == rows - 1 || nc == 0 || nc == cols - 1) {
answer = steps + 1;
} else {
maze[nr][nc] = '+';
qr[tail] = nr; qc[tail] = nc; qd[tail++] = steps + 1;
}
}
}
}
free(qr);
free(qc);
free(qd);
return answer;
}Edge Cases & Common Mistakes
- Counting the entrance as an exit: an entrance on the border is not an exit; mark it before the search.
- Marking cells when dequeued: cells get queued several times and the search slows down.
- A one-row or one-column maze: every cell is on the border, so any empty neighbour of the entrance is an exit.
- No reachable exit: return -1 once the queue is empty.
Summary
BFS from the entrance, with the entrance marked as a wall. The first empty border cell reached is the nearest exit; return its distance, or -1 if the queue runs out. O(m · n) time and space.
More practice: DSA interview questions with answers · patterns cheat sheet
