InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Nearest Exit from Entrance in Maze

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug