The naive approach is to BFS from each gate separately and track minimums, but that tanks your runtime on large grids.
Use a multi-source BFS starting from all gates simultaneously, updating empty rooms with their distance to the nearest gate. This ensures each cell is visited once, achieving O(mn) time complexity.
Pro tip: Emphasize that multi-source BFS is optimal because it processes all gates in parallel, avoiding redundant traversals and naturally handling unreachable rooms. Also, mention that modifying the grid in-place is safe since gates and walls are never overwritten.
Scan the grid to collect the coordinates of all gates (cells with value 0) and enqueue them for BFS.
Set up a queue with all gate coordinates and define the four possible movement directions (up, down, left, right).
While the queue is not empty, dequeue a cell and for each valid neighbor that is an empty room (INF), update its distance to current distance + 1 and enqueue it.
After BFS, any remaining INF cells are unreachable from any gate and should stay as INF.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.