InterviewPrepKit

Home / Coding / Graphs

Nearest Exit from Entrance in Maze

medium Original ↗
Solving tips
  • Every move costs 1, so 'shortest path on an unweighted grid' means BFS, not DFS or Dijkstra; O(m*n) time and space.
  • Block the entrance (mark it a wall) before searching so it can't be counted as an exit, then BFS outward and return steps+1 the first time you reach a border empty cell.
  • Mark cells visited the moment you enqueue them (not on dequeue) to keep each cell queued once and the work linear.
  • Pitfall: check the border condition on the neighbor you are about to enqueue, and return -1 if the queue drains without finding a non-entrance border cell.

Problem

You’re given an m x n grid maze. Each cell is either . (empty, walkable) or + (a wall). You also get entrance = [r, c], the coordinates of an empty cell where you start.

In one step you may move up, down, left, or right into an adjacent empty cell (you cannot step into walls or off the grid). An exit is any empty cell on the border of the maze — the first or last row, or the first or last column — other than the entrance itself.

Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no exit is reachable.

Examples

  • maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]1 — step up to (0,2), an empty border cell.
  • maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]2 — the entrance sits on the border but doesn’t count; walk right to (1,1) then (1,2), which is a border exit.
  • maze = [[".","+"]], entrance = [0,0]-1 — the only other cell is a wall, so no exit is reachable.

Constraints

  • 1 <= m, n <= 100
  • Every cell is . or +; the entrance is always an empty cell.
  • All edges have equal cost (each step = 1), which is what makes plain BFS optimal.

Think about it first

Hint 1 Every move costs exactly one step, so this is a shortest-path problem on an unweighted grid. What traversal expands outward in rings of increasing distance?
Hint 2 Breadth-first search from the entrance visits all cells at distance 1, then all at distance 2, and so on. The first time you pop a border cell (that isn't the entrance), that distance is the answer.
Hint 3 Track distance per level, mark cells visited as you enqueue them (turn them into walls or use a seen set) so you never revisit, and check the border condition when you dequeue. Return `-1` if the queue empties first.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.