Walls and Gates (LeetCode 286): Solution and Explanation
You get a grid of rooms where -1 is a wall, 0 is a gate and 2147483647 marks an empty room. Overwrite every empty room with its step distance to the closest gate, leaving rooms that cannot reach any gate untouched. The grid is modified in place.
Watch it run step by step
Try your own input and write the code →Intuition
The obvious first idea is to stand in each empty room and run a BFS outward until you hit a gate. That works, but every search can sweep most of the grid, so with m × n rooms the total cost climbs to O((m × n)²). On a 250 by 250 grid that is billions of steps, far too slow.
Flip the direction of the search. Instead of asking, for each room, where the nearest gate is, let every gate expand outward at the same time. Put all gates into one queue before the BFS starts. Because BFS processes cells in order of distance, the first wave from any gate to touch a room is the shortest one, so that room's distance is final the moment it is written.
The grid itself does the bookkeeping. A room still holding INF has not been reached yet, so the check rooms[nr][nc] == INF doubles as the visited test. Walls are never INF and gates are 0, so neither is ever overwritten, and no separate visited array is needed.
Approach: Multi-source BFS
- Return immediately if the grid is empty, then record
m,nand the sentinelINF = 2147483647. - Scan the whole grid and push the coordinates of every gate (value
0) into a deque. - Pop a cell
(r, c)from the front of the queue. - Look at its four neighbors. Skip any that fall outside the grid or do not hold
INF, since those are walls, gates or rooms already reached by a closer wave. - For each unreached room, write
rooms[r][c] + 1into it and append it to the queue. - Repeat until the queue empties. Rooms that still hold
INFhave no path to any gate and stay as they are.
Step-by-step example
rooms = [[INF,-1,0],[INF,INF,INF],[0,-1,INF]]
- The scan finds two gates, so the queue starts as
[(0,2), (2,0)]. - Pop
(0,2): its onlyINFneighbor is(1,2), which becomes 1. Pop(2,0): itsINFneighbor(1,0)becomes 1. The queue is now[(1,2), (1,0)]. - Pop
(1,2): neighbors(1,1)and(2,2)are stillINF, so both become 2 and join the queue. - Pop
(1,0):(1,1)is already 2 and is skipped, while(0,0)isINFand becomes 2. - Popping
(1,1),(2,2)and(0,0)finds no moreINFneighbors, so the queue drains. - The final grid is
[[2,-1,0],[1,2,1],[0,-1,2]]. Notice(1,1)got 2 from the top gate even though the bottom gate is also 2 away; ties do not matter.
Code: Python, Java, C++
1class Solution:
2 def wallsAndGates(self, rooms: List[List[int]]) -> None:
3 if not rooms:
4 return
5 INF = 2147483647
6 m, n = len(rooms), len(rooms[0])
7 queue = deque()
8
9 # Find all gates
10 for i in range(m):
11 for j in range(n):
12 if rooms[i][j] == 0:
13 queue.append((i, j))
14
15 # BFS from all gates simultaneously
16 dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
17 while queue:
18 r, c = queue.popleft()
19 for dr, dc in dirs:
20 nr, nc = r + dr, c + dc
21 if 0 <= nr < m and 0 <= nc < n and rooms[nr][nc] == INF:
22 rooms[nr][nc] = rooms[r][c] + 1
23 queue.append((nr, nc))1class Solution {
2 public void wallsAndGates(int[][] rooms) {
3 if (rooms.length == 0) return;
4 int INF = Integer.MAX_VALUE;
5 int m = rooms.length, n = rooms[0].length;
6 Queue<int[]> queue = new LinkedList<>();
7
8 for (int i = 0; i < m; i++) {
9 for (int j = 0; j < n; j++) {
10 if (rooms[i][j] == 0) queue.offer(new int[]{i, j});
11 }
12 }
13
14 int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
15 while (!queue.isEmpty()) {
16 int[] cell = queue.poll();
17 int r = cell[0], c = cell[1];
18 for (int[] d : dirs) {
19 int nr = r + d[0], nc = c + d[1];
20 if (nr >= 0 && nr < m && nc >= 0 && nc < n && rooms[nr][nc] == INF) {
21 rooms[nr][nc] = rooms[r][c] + 1;
22 queue.offer(new int[]{nr, nc});
23 }
24 }
25 }
26 }
27}1class Solution {
2public:
3 void wallsAndGates(vector<vector<int>>& rooms) {
4 if (rooms.empty()) return;
5 int INF = INT_MAX;
6 int m = rooms.size(), n = rooms[0].size();
7 queue<pair<int, int>> q;
8
9 for (int i = 0; i < m; i++) {
10 for (int j = 0; j < n; j++) {
11 if (rooms[i][j] == 0) q.push({i, j});
12 }
13 }
14
15 vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
16 while (!q.empty()) {
17 auto [r, c] = q.front(); q.pop();
18 for (auto [dr, dc] : dirs) {
19 int nr = r + dr, nc = c + dc;
20 if (nr >= 0 && nr < m && nc >= 0 && nc < n && rooms[nr][nc] == INF) {
21 rooms[nr][nc] = rooms[r][c] + 1;
22 q.push({nr, nc});
23 }
24 }
25 }
26 }
27};Time and space complexity
O(m × n)
Each cell enters the queue at most once, because it is only enqueued while it still holds INF and is overwritten in the same step. Every dequeued cell checks four neighbors, so total work is proportional to the number of cells.
O(m × n)
The grid is updated in place, but the queue can hold a large fraction of the cells at once, for example when most of the grid is gates or one wide frontier of rooms.
Other approaches
BFS from every empty room (time O((m × n)²), space O(m × n))
Run a separate BFS from each empty room and stop at the first gate found. It is simple to reason about but repeats the same exploration over and over, so it only makes sense for tiny grids.
DFS from each gate with distance pruning (time O(g × m × n) for g gates, space O(m × n))
Start a DFS at each gate and recurse into a neighbor only when the new distance is smaller than the value stored there. It gives correct answers but can revisit cells many times and risks deep recursion on large open grids.
Common mistakes
- Running a fresh BFS from each gate one at a time. A room filled by the first gate may later need a smaller value from another gate, so you either get wrong answers or must add extra comparisons and revisits.
- Marking a room only when it is dequeued instead of when it is enqueued. The same room can then be pushed several times from different neighbors in the same wave, which wastes time and memory.
- Comparing against the wrong sentinel. The empty value is exactly
2147483647; testing for something like> 0breaks once you have written distances into rooms. - Forgetting the bounds check before indexing
rooms[nr][nc]. In Python a negative index silently wraps around to the other side of the grid instead of raising an error.
Frequently asked questions
Why use multi-source BFS for walls and gates?
Because the question is distance to the nearest of many sources. Seeding the queue with all gates means the BFS layers expand from every gate together, so each room is first reached by its closest gate and is finalized in one pass.
What is the time complexity of walls and gates?
O(m × n). Every cell is enqueued at most once and each one inspects four neighbors, so the work grows linearly with the size of the grid.
Can I use DFS instead of BFS?
You can, but DFS does not visit cells in order of distance, so a room may be written with a long distance and later need correcting. That forces revisits and makes the worst case much slower than the single BFS pass.
Do I need a visited array?
No. A room that still holds INF is unvisited, and the moment you write a distance into it, it stops matching the INF check. The grid acts as its own visited set.