← Questions
Nearest exit from a maze
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Uber's coding round, last asked Feb 2026. It tests bfs and grids.
You get a maze as a grid of walls and open cells, and a starting cell inside it. You move one cell at a time up, down, left or right, through open cells only. An exit is any open cell on the border of the grid other than the starting cell. Return the fewest steps to reach an exit, or -1 if no exit can be reached.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
nearest_exit(maze: list[list[str]], entrance: tuple[int, int]) -> int—'+'is a wall and'.'is open.maze[entrance[0]][entrance[1]]is always'.'.
Example
maze = [["+", "+", ".", "+"],
[".", ".", ".", "+"],
["+", "+", "+", "."]]
nearest_exit(maze, (1, 2)) -> 1 # (0, 2) is on the border, one step up
maze = [["+", "+", "+"],
[".", ".", "."],
["+", "+", "+"]]
nearest_exit(maze, (1, 0)) -> 2 # the entrance is on the border but does not count; (1, 2) does
nearest_exit([[".", "+"]], (0, 0)) -> -1
Constraints
-
1 <= rows, cols <= 200.
Clarifying questions
- Does the entrance count as an exit if it lies on the border? (No.)
- Are diagonal moves allowed?
- Can I mark visited cells in the input grid?
- Should I return the path too?
What a strong answer covers
- Breadth-first search from the entrance; the first border cell dequeued is the nearest exit.
- Marking cells visited when they are enqueued, so no cell enters the queue twice.
- O(rows × cols) time and space.
- Tests: entrance on the border, no exit, an exit in a corner, a single-row maze.
Follow-ups
- Return the path to the exit.
- Several people start at different cells. Find, for each one, the nearest exit (one multi-source BFS from all exits).
- Some open cells cost more to cross. What replaces BFS?
Where it's asked
- Uber · Coding · Last asked Feb 202660 min · Two rounds; one is often object-oriented design (a parking lot, a meeting scheduler, an expression evaluator) · No AI, except a newer AI-assisted debugging round in some senior loops
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
