Problem Description
You are given an m x n grid called rooms. Each cell in the grid can have one of three values: -1 representing a wall or obstacle, 0 representing a gate, or INF (2147483647) representing an empty room. The goal is to fill each empty room with the number of steps to its nearest gate. If a gate cannot be reached from an empty room, its value remains INF.
Key Insights
- Use a multi-source Breadth-First Search (BFS) starting from all the gates, as this allows spreading the shortest distance to each empty room.
- Instead of starting from every empty room separately, starting from all gates simultaneously helps update all distances in one pass.
- Only update a room if the new calculated distance is smaller than its current value to prevent unnecessary processing.
- The problem is essentially a multi-source shortest path problem on a grid.
Space and Time Complexity
Time Complexity: O(m * n) where m and n are the dimensions of the grid, as each cell is processed at most once. Space Complexity: O(m * n) in the worst-case scenario used by the BFS queue.
Solution
The solution uses a multi-source BFS algorithm by initially enqueuing all the gate positions (cells with value 0). Then, for each cell obtained from the queue, check its four possible neighbors (up, down, left, right). If a neighbor is an empty room (INF), update its distance to be the current cell's distance plus one, and then enqueue the neighbor to process further. This ensures that each empty room gets the minimum distance from any gate.