15% off all plans & roadmaps Use code

See plans

Walls and Gates

Updated

TL;DR: Fill every empty room with its distance to the nearest gate, in place. Start one breadth-first search from all gates at once, so each room is reached first by its closest gate.

Problem

You are given a grid rooms where each cell is a room, a wall, or a gate. A value of -1 is a wall that cannot be entered. A value of 0 is a gate. A value of 2147483647 is an empty room whose distance has not been filled in yet.

You can move only up, down, left, or right, and you cannot pass through walls. Change rooms in place so that every empty room holds the fewest moves needed to reach any gate. If an empty room cannot reach a gate, leave it as 2147483647. The method returns nothing. The answer is the final content of rooms.

Example 1

Input: rooms = [[2147483647,-1,0],[2147483647,2147483647,2147483647],[-1,2147483647,-1]]
Output: [[4,-1,0],[3,2,1],[-1,3,-1]]
Explanation: the gate at the top right reaches the open cells through the middle row. Wall cells are unchanged.

Example 2

Input: rooms = [[2147483647,-1],[2147483647,2147483647]]
Output: [[2147483647,-1],[2147483647,2147483647]]
Explanation: there is no gate, so no empty room gets a finite distance.

Example 3

Input: rooms = [[0,2147483647,2147483647],[2147483647,-1,2147483647],[2147483647,2147483647,0]]
Output: [[0,1,2],[1,-1,1],[2,1,0]]
Explanation: each room takes the distance to the nearer of the two gates. The center wall stays -1.

Constraints

  • 1 <= rooms.length <= 250
  • 1 <= rooms[0].length <= 250
  • Every row in rooms has the same length as rooms[0].
  • Each rooms[i][j] is -1, 0, or 2147483647.
  • Adjacency is four-directional: up, down, left, and right.

Constraints that matter

  • The grid has up to 250 * 250 = 62,500 cells. A full search per empty room costs about 62,500 * 62,500 steps in the worst case, which is too slow.
  • Distances count moves between four-neighbors with equal cost. That makes this a shortest path in an unweighted graph, so breadth-first search is enough and Dijkstra is not needed.
  • Each cell holds only -1, 0, or 2147483647. The grid can double as the visited marker: a room that still holds 2147483647 is unvisited.
  • The largest real distance is under 62,500, so adding 1 to a distance never overflows a 32-bit int. Only the sentinel itself is near the limit, and you never add to it.
  • The method returns nothing, so you must write into rooms directly. Do not build a new grid and return it.

View on LeetCode

Hints

Hint 1

This is a shortest-path problem on an unweighted grid, so the pattern is graph BFS.

Hint 2

For each empty room, run a fresh BFS outward until you pop a gate.

Solution

Intuition

This is a shortest-path problem on an unweighted grid, so the pattern is graph BFS. Each non-wall cell is a node and each pair of adjacent non-wall cells is an edge. Breadth-first search reaches nodes in order of distance, which is exactly what you need.

Picture dropping a stone into every gate at the same instant, so every ripple spreads at equal speed. The first ripple to reach a room came from its nearest gate, and the queue is the ring of wavefronts.

The question asks for the distance to the nearest gate, not to a particular gate. That points to starting the search from the gates, not from the rooms. Put every gate in the queue at distance 0 before you begin. Then the search grows outward from all gates at the same speed, like ripples that start at the same moment.

Take Example 1. The only gate is at the top right. Its neighbors below get 1. Cells next to those get 2, then 3, then 4. The first wave to write a room is the earliest wave, so the value is the minimum and you never revisit it.

The grid doubles as the visited set. A room that still holds 2147483647 has not been reached. Walls hold -1 and gates hold 0, so a check for 2147483647 skips both automatically. Rooms that no wave reaches keep the sentinel, which is the required answer for unreachable rooms.

Watch the pattern animation

Worked example

Input: rooms = [[2147483647,-1],[2147483647,2147483647]]
Output: [[2147483647,-1],[2147483647,2147483647]]
Explanation: The grid has no gate. No search can ever start from a source, so every empty room stays at 2147483647 and the wall stays at -1. This case checks that your code leaves unreachable rooms alone.

Approach 1: Brute force: BFS from every empty room

For each empty room, run a fresh BFS outward until you pop a gate. The first gate you reach is the closest, and its depth is the answer for that room.

This is correct because BFS pops cells in order of distance. If the search empties its queue without meeting a gate, the room cannot reach one and keeps 2147483647. Each search needs its own visited marks. A stamp per search avoids clearing a whole grid every time.

Steps

  1. Walk over every cell. Skip it unless it still holds 2147483647.
  2. Give this search a fresh stamp and mark the start cell with it.
  3. Push the start cell with distance 0 into a queue.
  4. Pop a cell. If it is a gate, write its distance into the start cell and stop this search.
  5. Otherwise push each in-bounds neighbor that is not a wall and does not carry the current stamp. Mark it and give it distance + 1.
  6. If the queue empties, leave the start cell as 2147483647.

Dry run

On the example [[INF,-1],[INF,INF]] there are three empty rooms.

Room (0,0): the queue holds (0,0,0). Pop it, not a gate. The right neighbor is a wall. The bottom neighbor (1,0) is pushed with distance 1. Pop (1,0), not a gate, and push (1,1) with distance 2.

Pop (1,1). Its neighbors are a wall and a marked cell. The queue is empty with no gate found, so (0,0) stays INF.

Room (1,0) and room (1,1) run the same way. Each explores the other two open cells, finds no gate, and stays INF. The grid ends as [[INF,-1],[INF,INF]], which matches the output.

Complexity

TimeO((R * C)^2)
SpaceO(R * C)

Let R be rows and C be columns, so the grid has R * C cells. One BFS touches each cell at most once, so it costs O(R * C). There can be O(R * C) empty rooms, and each starts its own BFS, giving O((R * C)^2) time. The queue and the stamp grid each hold at most R * C entries, so space is O(R * C).

PythonTested in our runner

from collections import deque
from typing import List, Optional

class Solution:
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        INF = 2147483647
        rows, cols = len(rooms), len(rooms[0])
        mark = [[0] * cols for _ in range(rows)]
        stamp = 0
        for sr in range(rows):
            for sc in range(cols):
                if rooms[sr][sc] != INF:
                    continue
                stamp += 1
                mark[sr][sc] = stamp
                queue = deque([(sr, sc, 0)])
                while queue:
                    r, c, d = queue.popleft()
                    if rooms[r][c] == 0:
                        rooms[sr][sc] = d
                        break
                    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] != -1 and mark[nr][nc] != stamp:
                            mark[nr][nc] = stamp
                            queue.append((nr, nc, d + 1))

Approach 2: BFS from each gate with pruning

What's slow: the number of searches equals the number of empty rooms, and rooms near each other repeat almost the same exploration. Gates are usually far fewer than rooms, so searching outward from the many to find the few wastes work.

The insight that fixes it: flip the direction. Run one BFS from each gate and write distances as you go. Let a search enter a cell only when the new distance is strictly smaller than the value already stored there.

Walls hold -1 and gates hold 0, so no distance ever beats them and they are skipped for free. The stored value acts as both the distance and the visited check.

Steps

  1. Scan the grid for cells equal to 0.
  2. For each gate, start a queue holding only that gate.
  3. Pop a cell and read its current distance.
  4. For each in-bounds neighbor, check whether its stored value is greater than the current distance + 1.
  5. If so, overwrite it with distance + 1 and push it.
  6. Repeat for the next gate until all gates are processed.

Dry run

On the example [[INF,-1],[INF,INF]] the scan finds no cell equal to 0. No gate means no queue is ever created, so no cell is written.

To see the pruning work, take Example 3 for one step. Gate (0,0) writes 1 into (0,1) and (1,0), then 2 into (0,2) and (2,0). Gate (2,2) later reaches (0,2) with distance 2, which is not smaller than the stored 2, so it stops there. For the page example the grid stays [[INF,-1],[INF,INF]], which is the expected output.

Complexity

TimeO(G * R * C)
SpaceO(R * C)

Let G be the number of gates. Inside a single BFS, cells come out in order of distance from that gate, so a cell is written at most once per search and each search costs O(R * C). G searches cost O(G * R * C).

The queue holds at most R * C cells, so extra space is O(R * C). In the worst case G is proportional to R * C, so this is no better than O((R * C)^2) there.

PythonTested in our runner

from collections import deque
from typing import List, Optional

class Solution:
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        rows, cols = len(rooms), len(rooms[0])
        for gr in range(rows):
            for gc in range(cols):
                if rooms[gr][gc] != 0:
                    continue
                queue = deque([(gr, gc)])
                while queue:
                    r, c = queue.popleft()
                    nd = rooms[r][c] + 1
                    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        nr, nc = r + dr, c + dc
                        # only improve strictly; walls (-1) and gates (0) never qualify
                        if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] > nd:
                            rooms[nr][nc] = nd
                            queue.append((nr, nc))
Graph BFS - Connected Components / Island Counting pattern infographic for Walls and Gates

Solution pattern

Graph BFS - Connected Components / Island Counting

Part of Graph Traversal Patterns (DFS & BFS)

Approach 3: Multi-source BFS from all gatesOptimalGraph BFS - Connected Components / Island Counting

What's slow: each gate still runs its own search, and a room can be rewritten once per gate before it settles. In a grid with many gates, the same region is walked again and again, and the early writes are thrown away.

The insight that fixes it: put every gate in one queue before the search starts. BFS then handles all distance-0 cells, then all distance-1 cells, and so on. A room is first written by the nearest gate, because that gate's wave arrives earlier than any other. So you write each room once and mark it visited by that same write.

Why it is correct. The queue always holds cells in order of distance, with values differing by at most one. So when a cell is popped, its value is already its true shortest distance. A room is written only the first time it is reached, and any later wave arrives at the same or a greater distance.

Steps

  1. Scan the grid once and push every cell holding 0 into a single queue.
  2. Pop the front cell. Its value is its final distance.
  3. Check its four neighbors for being in bounds.
  4. Skip any neighbor that is not 2147483647. That excludes walls, gates and rooms already filled.
  5. Write the popped cell's value + 1 into the neighbor and push the neighbor.
  6. Stop when the queue is empty. Rooms never touched stay 2147483647.

Dry run

Trace on the page example [[INF,-1],[INF,INF]]. The table shows each step and the state after it.

StepActionQueueGrid
1Scan (0,0): value INF, not a gateempty[[INF,-1],[INF,INF]]
2Scan (0,1): value -1, not a gateempty[[INF,-1],[INF,INF]]
3Scan (1,0): value INF, not a gateempty[[INF,-1],[INF,INF]]
4Scan (1,1): value INF, not a gateempty[[INF,-1],[INF,INF]]
5Queue is empty, so the BFS loop never runsempty[[INF,-1],[INF,INF]]

The final grid equals the expected output. For a grid with a gate, such as Example 1, the queue would start as [(0,2)]. Popping it writes 1 into (1,2), then 2 into (1,1), then 3 into (1,0) and (2,1), then 4 into (0,0).

Complexity

TimeO(R * C)
SpaceO(R * C)

Let R be rows and C be columns. The initial scan visits R * C cells. A cell enters the queue at most once, because it is pushed only when it holds 2147483647 and the push overwrites that value.

Each popped cell checks four neighbors, which is constant work, so the loop costs O(R * C) in total. The queue can hold up to R * C cells, so space is O(R * C), and no separate visited grid is needed.

PythonTested in our runner

from collections import deque
from typing import List, Optional

class Solution:
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        INF = 2147483647
        rows, cols = len(rooms), len(rooms[0])
        queue = deque()
        # every gate is a distance-0 source
        for r in range(rows):
            for c in range(cols):
                if rooms[r][c] == 0:
                    queue.append((r, c))
        while queue:
            r, c = queue.popleft()
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = r + dr, c + dc
                # INF means an unvisited empty room
                if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == INF:
                    rooms[nr][nc] = rooms[r][c] + 1
                    queue.append((nr, nc))

Common mistakes

  • Starting the search from empty rooms and stopping at the first gate for the whole grid. This is the brute force and it repeats work. Start from all gates in one queue instead.
  • Pushing only one gate before the loop, for example queue.append(first_gate). Distances then measure the path to that single gate. Push every cell equal to 0 before you pop anything.
  • Checking rooms[nr][nc] != -1 as the only guard in the multi-source version. That lets BFS re-enter gates and filled rooms and overwrite good values. Require == 2147483647 so walls, gates and filled rooms are all skipped.
  • Writing the distance after the pop instead of at push time, so a room can be queued twice by two neighbors. Write rooms[nr][nc] = rooms[r][c] + 1 at the moment you push. That write is also the visited mark.
  • Using a Python list with pop(0) or a JavaScript array with shift() as the queue. Both cost O(n) per removal and slow a 250 by 250 grid. Use deque.popleft() in Python and a head index in JavaScript.
  • Using recursive DFS from each gate on a large open grid. The recursion depth can reach 62,500 and overflow the Python default stack limit. Use an iterative BFS with a queue.

Edge cases

  • A grid with no gates, such as [[2147483647,-1],[2147483647,2147483647]]. The queue starts empty and the grid is returned unchanged.
  • A single cell holding 0, -1, or 2147483647. Nothing changes in any of the three cases, because there is no neighbor to update.
  • A room fully enclosed by walls with a gate elsewhere. It is never reached, so it keeps 2147483647.
  • Two gates at equal distance from a room, as in Example 3. The first wave to arrive writes the value, and both waves would write the same number.
  • A full 250 by 250 grid with one gate in a corner. The farthest room gets distance 498, and the queue stays within 62,500 entries.
  • A grid made only of gates and walls. There are no empty rooms, so the BFS pops cells and finds nothing to write.

Follow-ups interviewers ask

Why does the order of the queue guarantee the minimum distance?
BFS pops cells in nondecreasing distance because every push adds exactly 1 to a popped value. By induction, once a cell at distance d is popped, every cell at distance d or less has already been pushed. So the first write to a room comes from the smallest possible d + 1. Later writes could never be smaller, and the room is already marked as filled.
What if moving into a cell had different costs?
BFS no longer works because the first arrival is not the cheapest. Use Dijkstra with a min-heap seeded with every gate at cost 0. Pop the cheapest cell, relax its neighbors, and push any improvement. Time becomes O(R * C * log(R * C)). With only costs 0 or 1 you can use a 0-1 BFS with a deque.
Can you solve it with DFS, and what is the catch?
Yes. Run a DFS from each gate and overwrite a room only when the new distance is smaller. The answers are correct, but a cell can be rewritten many times, so there is no clean O(R * C) bound. Recursion depth can also reach R * C, which is a problem in Python. BFS gives each cell a single write and avoids deep recursion.

Walls and Gates FAQ

What is the time complexity of Walls and Gates?

The multi-source BFS runs in O(R * C), where R and C are the grid dimensions. Each cell is pushed at most once and each pop does four neighbor checks. The brute force that searches from every empty room is O((R * C)^2).

Why use multi-source BFS for Walls and Gates?

Every room needs the distance to its nearest gate, and BFS reaches cells in order of distance. Starting from all gates at once means the first wave to touch a room is the closest one. You compute every answer in one pass instead of one search per room.

Can Walls and Gates be solved in O(1) extra space?

Not with BFS. The queue can hold up to R * C cells in the worst case, so extra space is O(R * C). Only the visited grid is free, because the room values store it. A recursive DFS also uses O(R * C) stack depth in the worst case.

How do I solve Walls and Gates in Python without a time limit error?

Seed a collections.deque with every gate, then call popleft() in a loop. Write rooms[r][c] + 1 into each neighbor that still equals 2147483647 and push it. Avoid list.pop(0), which is O(n) per call.

Is Walls and Gates the same as the Islands and Treasure problem?

The task is the same. Islands and Treasure uses the same grid, with treasure chests in place of gates and the same sentinel for empty land. The multi-source BFS solution carries over unchanged.

What does the 2147483647 value mean in Walls and Gates?

It is the largest 32-bit integer, used as infinity for an empty room not yet reached. After the BFS, any room that still holds it has no path to a gate. That is the correct final value for such rooms.

Asked at

See which companies ask this — Pro

Practise it