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 - BFS Solution INPUT 4x4 Grid (m x n) INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF Gate (0) Wall (-1) Empty (INF) Values: INF = 2147483647 Gates at: (0,2), (3,0) ALGORITHM STEPS 1 Find All Gates Add gates (0,2) and (3,0) to BFS queue 2 Multi-source BFS Process all gates at same level simultaneously 3 Explore Neighbors For each cell, check 4 directions (up/down/left/right) 4 Update Distance If empty room (INF), set dist = current + 1 BFS Queue Progress: L0: (0,2),(3,0) L1: (0,3),(1,2),(2,0) ... Time: O(m*n) Space: O(m*n) for queue FINAL RESULT Distance to Nearest Gate 3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4 Distance Scale: 0 1 2 3+ Output Array: [[3,-1,0,1], [2,2,1,-1], [1,-1,2,-1], [0,-1,3,4]] Key Insight: Multi-source BFS starts from ALL gates simultaneously, expanding outward level by level. This ensures each empty room gets the shortest distance to its nearest gate without redundant visits. Unlike single-source BFS from each gate, this approach visits each cell only once - achieving O(m*n) time. TutorialsPoint - Walls and Gates | BFS Approach
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