← Microsoft Interview Insights
My first instinct was to BFS from every empty room individually and find the nearest gate.
Use a multi-source BFS starting from all gates simultaneously, propagating distances to empty rooms level by level. This ensures each room is reached via the shortest path from any gate, and walls are never enqueued. Unreachable rooms remain unchanged.
Pro tip: Mention that multi-source BFS is optimal because it processes each cell once, achieving O(mn) time, and that using a queue with level-order traversal avoids the need for a priority queue. Also note that you can modify the grid in-place to store distances, saving space.
Confirm the representation of walls, gates, and empty rooms (e.g., -1, 0, INF). Clarify that unreachable rooms should remain as INF (or original value).
Scan the grid and enqueue the coordinates of every gate. This sets up the multi-source BFS.
While the queue is not empty, pop a cell and explore its four neighbors. If a neighbor is an empty room (INF), update its distance to current distance + 1 and enqueue it.
After BFS, the grid contains shortest distances for reachable rooms; unreachable rooms remain INF. Return the grid.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.