Nearest Exit from Entrance in Maze solution explained
Nearest Exit from Entrance in Maze is a single-source BFS on a grid that stops early: start at the entrance, expand through open cells level by level, and return the step count the moment you reach an open cell on the outer edge that is not the entrance itself. If the queue runs dry first, there is no exit and the answer is -1.
By Evin JohnPublished 7 min read
The problem in plain words
A maze is a grid where '.' is an open cell and '+' is a wall. You are given the row and column of an entrance, which is always an open cell. From any cell you may step up, down, left or right into an open cell. An exit is any open cell on the outer edge of the grid, with one exception: the entrance does not count as an exit, even if it lies on the edge. Return the number of steps on the shortest route from the entrance to an exit, or -1 if no exit can be reached.
| Maze | Entrance | Answer | Reason |
|---|---|---|---|
| +.++ / +..+ / ++.+ | (0, 1) | 3 | The entrance is on the top edge but does not count; the nearest real exit is the bottom opening at (2, 2) |
| +++++ / +...+ / +.+.+ / +++.+ | (1, 1) | 4 | Right along the corridor, then down to the gap at (3, 3) |
| +.+ / +.+ / +++ | (1, 1) | 1 | One step up reaches the opening at (0, 1) |
| . | (0, 0) | -1 | The only open cell is the entrance |
Confirm a couple of details before writing code. Are coordinates given as [row, column]? Can the maze be a single row or a single column, where almost every cell lies on the border? Both come up in tests, and the single-row case is where off-by-one mistakes in the border check usually show.
What makes it different from a plain maze BFS
Most maze problems give you one target cell. Here the target is a set: every open border cell except one. You do not need to list that set in advance. A cell is an exit if its row is 0 or the last row, or its column is 0 or the last column, and it is not the entrance. Checking that condition on each cell as BFS reaches it is enough.
The entrance exclusion is easier than it looks. Since BFS marks the entrance as seen before the loop starts, it is never generated again as a neighbor. If you only test the exit condition on newly generated neighbors, the entrance can never be reported, and no special case is needed.
Slow approach: all distances, then pick the best border cell
A straightforward brute force fills a distance table for every cell. Start with 0 at the entrance and infinity elsewhere, then sweep the grid repeatedly, lowering any open cell whose neighbor offers a shorter route, until a full sweep changes nothing. Finally scan the border, skip the entrance, and take the smallest finite value. It is easy to trust and makes a solid test oracle, but each sweep costs O(R · C) and you may need up to O(R · C) sweeps on a winding maze, so the worst case is quadratic in the grid size. Even a single full BFS here does extra work, because it keeps going long after the nearest exit is known.
Main approach: BFS with an early return
- SeedMark the entrance seen and push it with distance 0.
- ExpandPop a cell and look at its four neighbors. Skip anything off the grid, any wall, and any cell already seen.
- Test on generationIf the neighbor lies on the border, return the current distance plus one. Because the entrance is already seen, it can never trigger this.
- Otherwise enqueueMark the neighbor seen and push it with distance plus one. If the queue empties, return -1.
from collections import deque
def nearest_exit(maze, entrance):
rows, cols = len(maze), len(maze[0])
sr, sc = entrance
seen = {(sr, sc)}
queue = deque([(sr, sc, 0)])
while queue:
r, c, d = queue.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and maze[nr][nc] == "." and (nr, nc) not in seen:
if nr in (0, rows - 1) or nc in (0, cols - 1):
return d + 1
seen.add((nr, nc))
queue.append((nr, nc, d + 1))
return -1function nearestExit(maze, entrance) {
const rows = maze.length, cols = maze[0].length;
const [sr, sc] = entrance;
const seen = maze.map((row) => row.map(() => false));
seen[sr][sc] = true;
const queue = [[sr, sc, 0]];
for (let head = 0; head < queue.length; head++) {
const [r, c, d] = queue[head];
for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
if (maze[nr][nc] !== "." || seen[nr][nc]) continue;
if (nr === 0 || nc === 0 || nr === rows - 1 || nc === cols - 1) return d + 1;
seen[nr][nc] = true;
queue.push([nr, nc, d + 1]);
}
}
return -1;
}Returning when a neighbor is generated, rather than when it is popped, is safe in an unweighted grid. Every cell at distance d + 1 is generated by some cell at distance d, and all cells at distance d are popped before any at d + 1, so the first border cell generated is at the smallest possible distance. It also saves processing a whole extra layer.
If the interviewer prefers not to keep a separate seen structure, you can overwrite visited cells in the maze with '+'. That saves memory but mutates the input, so ask before doing it.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Relax distances until stable | O((R · C)²) worst case | O(R · C) |
| Full BFS, then scan the border | O(R · C) | O(R · C) |
| BFS with early return | O(R · C) worst case, often much less | O(R · C) |
Edge cases to test
- The entrance is on the border, and it is the only open border cell: the answer is -1.
- The entrance is on the border and another exit is right next to it: the answer is 1.
- A one-cell maze, which can never have an exit.
- A single row such as '...' with the entrance in the middle: both ends are exits one step away.
- An entrance boxed in by walls on all four sides.
- A large open maze, where the early return should make the search fast.
Common mistakes
- Checking the exit condition when a cell is popped and forgetting to exclude the entrance, so a border entrance returns 0.
- Writing the border test with the wrong bounds, such as comparing to rows instead of rows - 1.
- Treating corners or edges as exits even when they are walls.
- Marking cells seen only after popping them, which lets the same cell enter the queue several times.
- Swapping row and column when reading the entrance pair.
- Using DFS and returning the first exit found, which is not necessarily the nearest.
A sample explanation
Fictional example
- Candidate
- This is shortest path in an unweighted grid from one source, so BFS. The goal is any open border cell, which I can test with a simple condition on row and column.
- Candidate
- The entrance never counts as an exit. I'll mark it seen before the loop and only test neighbors as I generate them, so it can't be returned by accident.
- Interviewer
- What if there's no way out?
- Candidate
- Then the queue empties and I return -1. Worst case I touch every open cell once, so it's linear in the size of the maze.
Related problems in this set
Walls and Gates flips this setup around, seeding many sources at once and filling every room with a distance. Shortest Path Visiting All Nodes moves from grids to general graphs and adds a bitmask so the search knows which nodes it has covered. The algorithm interview questions page has more on choosing between BFS and DFS.
Practicing with Natively
Natively can be useful while you rehearse grid problems like this one. In practice mode it can read the maze statement from a screenshot and sketch a BFS plan, which you can hold up against your own after a timed attempt. It also transcribes the mock interview on your computer, so you can confirm you raised the entrance rule without being prompted. See the AI interview assistant page for more.
Questions people ask
How do you solve Nearest Exit from Entrance in Maze?
Run BFS from the entrance through open cells. When you generate a neighbor that is on the outer edge of the grid, return the current distance plus one. If the queue empties, return -1.
Does the entrance count as an exit?
No, even when it sits on the border. Marking the entrance as seen before the loop and testing only newly generated cells keeps it from ever being returned.
Why is it safe to return when a cell is generated rather than popped?
In an unweighted grid every cell at distance d + 1 is generated while processing distance d, and BFS finishes distance d first, so the first border cell generated is the closest.
What is the time complexity?
O(R · C) in the worst case, since each open cell enters the queue at most once. The early return often stops much sooner.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
