Compute nearest-exit distances in a grid
Company: DoorDash
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: Compute nearest-exit distances in a grid evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= m, n <= 250 (typical interview bound)
- Each cell is -1 (wall), 0 (exit), or 2147483647 (empty room).
- The grid may contain zero exits (then every room stays 2147483647).
- Distances use 4-directional (up/down/left/right) Manhattan-style moves; you cannot pass through walls.
Examples
Input: ([[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]],)
Expected Output: [[3, -1, 0, 1], [2, 2, 1, -1], [1, -1, 2, -1], [0, -1, 3, 4]]
Explanation: Canonical Walls-and-Gates example. Multi-source BFS from the two exits (row0 col2 and row3 col0) fills every reachable room with its shortest 4-directional distance.
Input: ([[0]],)
Expected Output: [[0]]
Explanation: Single cell that is already an exit — nothing to fill.
Input: ([[2147483647]],)
Expected Output: [[2147483647]]
Explanation: A lone room with no exit anywhere stays at the sentinel value (unreachable).
Input: ([[-1]],)
Expected Output: [[-1]]
Explanation: A lone wall remains unchanged.
Input: ([[0,2147483647],[2147483647,-1]],)
Expected Output: [[0, 1], [1, -1]]
Explanation: Both rooms are one step from the single exit; the wall is untouched.
Input: ([],)
Expected Output: []
Explanation: Empty grid edge case — return as-is without error.
Input: ([[2147483647,2147483647],[2147483647,0]],)
Expected Output: [[2, 1], [1, 0]]
Explanation: Exit in the bottom-right corner; the far corner room is 2 moves away, the two adjacent rooms 1 move.
Hints
- A separate BFS from every room is O((m*n)^2). Invert the problem: BFS outward from the exits instead.
- Seed a single queue with the coordinates of ALL exits (cells equal to 0) before starting BFS — this is multi-source BFS.
- When you pop a cell, push each neighbor that still equals the sentinel 2147483647 and set its value to current + 1. Because BFS expands in layers of increasing distance, the first time you reach a room is its shortest distance, so no revisits and no explicit visited set are required.
- Walls (-1) and already-filled rooms are simply never enqueued because their value is not the sentinel.
- Follow-up (3D): use 6 neighbor offsets and (floor, row, col) tuples. Follow-up (weighted moves): replace the FIFO queue with a min-heap (Dijkstra) keyed by accumulated cost.