2Brute2Best
🔥0

Nearest Exit from Entrance in Maze

Medium·LeetCode #1926Basic Anchor
LeetCode
30-Second Mental ModelGraph BFS → Grid shortest path (BFS from one source)
Complexity:O(3^(m · n))→O(m · n)
Key Insight

Run a breadth-first search from the entrance. It visits cells in rings of equal distance: all cells 1 step away, then all cells 2 steps away, and so on. The first border cell it pops is the nearest exit, so the search can stop there.

Core Validity Invariant

A cell is popped only after every cell that is closer to the entrance, so the first border cell popped is the nearest exit. The entrance is 0 steps away and is never counted.

01

Problem

You are given a maze as a grid. Each cell is an empty cell (.) or a wall (+). You are also given the entrance, an empty cell where you start.

In one step you can move up, down, left or right into an empty cell. An exit is an empty cell on the border of the maze. The entrance does not count as an exit, even when it sits on the border.

Return the number of steps to the nearest exit, or -1 if no exit can be reached.

Input

maze, an m × n grid of . and +, and entrance = [row, col], an empty cell.

Output

The number of steps to the nearest reachable exit, or -1 if there is none.

Example 1
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1, 2]
Output: 1

The exit at [0, 2] is one step up from the entrance. The other exits are farther away, or walled off.

Example 2
Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1, 0]
Output: 2

The entrance is on the left border, but it is not an exit. The only exit is [1, 2], two steps to the right.

Example 3
Input: maze = [[".","+"]], entrance = [0, 0]
Output: -1

There is no exit. The only other cell is a wall.

Constraints
  • • 1 ≤ m, n ≤ 100
  • • Each cell is `.` (empty) or `+` (wall).
  • • The entrance is always an empty cell.
02

First, think yourself

Before opening any solution, try to answer these on paper. Use hints only when stuck — each hint is counted.

  1. 1.

    Is the answer the length of any path to an exit, or the length of the shortest one?

  2. 2.

    If I try all four directions from the entrance at the same time, which border cell can I reach first?

  3. 3.

    Does the entrance count as an exit when it sits on the border?

  4. 4.

    If a depth-first search finds an exit, is that exit guaranteed to be the nearest one?

  5. 5.

    After k rounds of a search, which cells are known to be exactly k steps away?

03

Brute force approach

05

Optimized approach

06

Why does this algorithm work?

07

Dry run

08

All approaches compared

ApproachIdeaTimeSpace
Brute ForceWalk every simple path from the entrance; keep the shortest one that reaches an exitO(3^(m · n))O(m · n)
OptimalBFS by distance from the entrance; the first border cell popped is the nearest exitO(m · n)O(m · n)
09

Why does this belong to this pattern?

Clues in the problem statement
  • “steps from the entrance”Every move costs the same, so the distance is the number of moves. A BFS gives the shortest distance to every cell.
  • “nearest exit”Stop at the first exit found in distance order, not at any exit the search happens to reach.
  • “empty cells and walls in a grid”The grid is a graph: each empty cell is a node and each move is an edge.
Unweighted grid+shortest number of steps+one source, BFS by distance→Graph BFS → Grid shortest path (BFS from one source)

This is the anchor of the grid-shortest sub-pattern. Every move costs one step, so BFS gives the true distance to every cell. The only twist is the stop rule: the first border cell popped is the answer, not the first one a DFS happens to reach. The next two questions keep the BFS and change what counts as a step or a state.

10

Don't make this mistake

Counting the entrance as an exit
✗ if (r == 0 || c == 0 || r == m - 1 || c == n - 1) return steps;
✓ if (steps > 0 && (r == 0 || c == 0 || r == m - 1 || c == n - 1)) return steps;

The second example's entrance [1, 0] is on the left border. Without the steps > 0 check the first pop returns 0, but the correct answer is 2. The entrance is never an exit.

Pattern confusion: DFS returns the first exit it finds
✗ // DFS from the entrance; return the steps at the first border cell reached
✓ // BFS by distance; the first border cell popped is the nearest one

On the dry-run maze a DFS that tries up, down, left, right first walks to a border cell 5 steps away. The nearest exit is 3 steps away at (1,4). A depth-first search follows one path to its end, so the first exit it reaches is not the closest.

Forgetting the seen grid
✗ queue.push({nr, nc}); // push every open neighbour, every time
✓ if (seen[nr][nc]) continue; seen[nr][nc] = true; queue.push({nr, nc});

Take the maze ++++ / +..+ / +..+ / ++++ with the entrance at (1,1). The four interior cells form a loop with no border cell in it, so without seen the queue keeps refilling forever and the search never ends. With seen the queue empties and the answer is -1.

11

Want to implement this?

Write it yourself on LeetCode, then come back and compare your code with the solutions above.

Open coding workspace
How did it go?
Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.