Walls And Gates
MediumNeetCode 150 GraphsDoorDashProblem
A building is a grid of rooms. A cell is -1 for a wall, 0 for a gate, or 2147483647 (call it INF) for an empty room.
Fill each empty room with the number of steps to its nearest gate, moving up, down, left or right and never through a wall. If a room cannot reach any gate, leave it as INF.
Change the grid in place; the method returns nothing.
Constraints
- 1 ≤ rows, cols ≤ 250
- rooms[r][c] is -1, 0 or 2147483647
Examples: pick one to animate
Solutions
Time: Every room enters the queue at most once, because a room stops being INF the moment it is reached. Each pop checks 4 neighbors.
Space: In the worst case (a grid with many gates and rooms) the queue holds O(rows · cols) cells.
Search from the gates, not from every room. Put all gates in a queue together and run BFS: the first time a wave reaches an INF room, that is the shortest distance
from the nearest gate, so write distance + 1 into it. A filled room is no longer INF, so it is never visited twice and rooms behind walls simply stay INF.