Walls and Gates - Problem

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 2³¹ - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647

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
Walls and Gates: Fill Empty Rooms with Distance to Nearest GateInputINF-10INFINF0Output2-10310Empty RoomWallGateMulti-source BFS propagates distances from all gates simultaneouslyEach empty room gets filled with shortest distance to any gateTime: O(mn) | Space: O(mn)
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
Asked in
Google 42 Facebook 38 Amazon 35 Microsoft 28
89.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen