Walls and Gates - Problem
Imagine you're designing a smart navigation system for a building! You have an m ร n grid representing rooms in a building, where each cell can be:
-1: A wall or obstacle (impassable)0: A gate (exit point)INF: An empty room (represented as2147483647)
Your task is to fill each empty room with the shortest distance to its nearest gate. If a room cannot reach any gate, it should remain INF.
Example: If a room is 3 steps away from the nearest gate, replace INF with 3.
Think of this as calculating evacuation distances - how quickly can someone get from any room to the nearest exit?
Input & Output
example_1.py โ Basic Building Layout
$
Input:
rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
โบ
Output:
[[3,-1,0,1],[2,1,2,-1],[1,-1,3,-1],[0,-1,2,3]]
๐ก Note:
Starting from gates at (0,2) and (3,0), we calculate shortest distances: rooms adjacent to gates get distance 1, rooms 2 steps away get distance 2, etc. Walls (-1) remain unchanged.
example_2.py โ Single Gate
$
Input:
rooms = [[2147483647,2147483647,0],[2147483647,-1,2147483647]]
โบ
Output:
[[2,1,0],[3,-1,1]]
๐ก Note:
With only one gate at (0,2), distances radiate outward: adjacent rooms get 1, rooms 2 steps away get 2, etc. The bottom-left room requires 3 steps to reach the gate.
example_3.py โ Unreachable Room
$
Input:
rooms = [[0,-1,2147483647]]
โบ
Output:
[[0,-1,2147483647]]
๐ก Note:
The rightmost room is completely blocked by the wall and cannot reach the gate, so it remains INF (2147483647).
Visualization
Tap to expand
Understanding the Visualization
1
Identify All Exits
Mark all emergency exits (gates) as starting points with distance 0
2
Simultaneous Expansion
From all exits, simultaneously mark adjacent rooms with distance 1
3
Ripple Effect
Continue expanding outward like ripples, marking rooms with distances 2, 3, 4...
4
Optimal Distances
Each room now shows the shortest evacuation path to any exit
Key Takeaway
๐ฏ Key Insight: Multi-source BFS from all gates simultaneously guarantees each room gets the shortest possible distance to any exit in optimal O(mn) time.
Time & Space Complexity
Time Complexity
O(mn)
Each cell is visited at most once during the BFS traversal
โ Linear Growth
Space Complexity
O(mn)
Queue can contain up to mn cells in worst case (all cells are gates)
โก Linearithmic Space
Constraints
- m == rooms.length
- n == rooms[i].length
- 1 โค m, n โค 250
- rooms[i][j] is -1, 0, or 231 - 1
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code