Walls and Gates - Problem
You are given an m x n grid rooms initialized with these three possible values:
-1- A wall or an obstacle0- A gateINF- Infinity means an empty room. We use the value2³¹ - 1 = 2147483647to representINFas you may assume that the distance to a gate is less than2147483647
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.
Input & Output
Example 1 — Basic Grid with Gates and Walls
$
Input:
rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
›
Output:
[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
💡 Note:
Gates at (0,2) and (3,0) spread their distances. Room at (0,0) is 3 steps from nearest gate, room at (0,3) is 1 step from gate at (0,2).
Example 2 — Single Room
$
Input:
rooms = [[-1]]
›
Output:
[[-1]]
💡 Note:
Only a wall, no changes needed since there are no gates or empty rooms.
Example 3 — Unreachable Room
$
Input:
rooms = [[2147483647,-1],[0,2147483647]]
›
Output:
[[2147483647,-1],[0,2147483647]]
💡 Note:
Gate at (1,0) cannot reach room at (0,0) due to wall at (0,1). Room at (1,1) cannot reach gate either.
Constraints
- m == rooms.length
- n == rooms[i].length
- 1 ≤ m, n ≤ 250
- rooms[i][j] is -1, 0, or 2³¹ - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
Grid with gates (0), walls (-1), and empty rooms (INF)
2
Distance Propagation
BFS spreads distances from all gates simultaneously
3
Final Result
Each empty room filled with shortest distance to any gate
Key Takeaway
🎯 Key Insight: Start BFS from all gates at once instead of searching from each room individually
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code