Walls and Gates
You are given an `m x n` grid `rooms` initialized with these three possible values. - `-1` A wall or an obstacle. - `0` A gate. - `INF` Infinity means an empty room. We use the value `2147483647` (2^31 - 1) as `INF` to represent infinity. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with `INF`.
Examples
Constraints
m == rooms.lengthn == rooms[i].length1 <= m, n <= 250rooms[i][j] is -1, 0, or 2147483647.
Breadth-First Search (BFS)
Approach
1. Intuition: We need to find the shortest distance from each empty room to the nearest gate. If we start BFS from every empty room, it would be inefficient. Instead, we can start BFS from ALL gates simultaneously (multi-source BFS). 2. First, we scan the grid to find all gates (cells with value `0`) and add their coordinates to a queue. 3. We initialize our BFS queue with all the gates. Since we process the queue layer by layer, the first time we reach an empty room, we are guaranteed to have found the shortest path to it from a gate. 4. We define the 4 possible directions (up, down, left, right). 5. While the queue is not empty, we pop a cell `(r, c)`. 6. For each neighbor of `(r, c)`, if it is out of bounds or NOT an empty room (meaning it's a wall, another gate, or an already visited empty room), we skip it. 7. Otherwise, the neighbor is an unvisited empty room. Its distance to a gate is the distance of `(r, c)` plus 1. We update the neighbor's value in the grid and push it into the queue for further exploration. 8. We repeat this until the queue is empty. The grid is modified in-place with the shortest distances.
Complexity Analysis
Time complexity is O(m * n) because we visit each cell at most once. Space complexity is O(m * n) since the queue could contain at most m * n elements.