Walls and Gates solution explained

Walls and Gates is the textbook case for multi-source breadth-first search: put every gate in the queue at distance 0, then expand outward, and the first time the search reaches an empty room, that distance is the room's nearest gate. Each cell is written once, so the whole grid is filled in O(R · C) time, and the grid itself doubles as the visited set.

By Published 8 min read

The problem in plain words

You get a rectangular floor plan as a grid of integers. A -1 is a wall, a 0 is a gate, and the value 2147483647 (the largest 32-bit signed integer, written INF below) marks an empty room. Moving one cell up, down, left or right takes one step, and you cannot pass through walls. For every empty room, overwrite its value with the number of steps to the closest gate. If a room is sealed off from all gates, leave it as INF. Change the grid in place and return nothing.

Grids built for this page (rows separated by slashes)
BeforeAfterNote
[INF, -1, 0] / [INF, INF, INF] / [0, -1, INF][2, -1, 0] / [1, 2, 1] / [0, -1, 2]Two gates; the middle room is two steps from both
[INF, INF, INF, 0][3, 2, 1, 0]One row, distances count down toward the gate
[INF, -1] / [-1, 0][INF, -1] / [-1, 0]The top-left room is walled in and keeps INF
Grids built for this page (rows separated by slashes). Scroll sideways on a small screen.

Clarify two things early. Is the in-place update required, or may you return a new grid? And does the sentinel really equal 2147483647, or should you treat any value above some bound as empty? The code below compares against the exact sentinel.

Slow approach: search from each room

The literal reading suggests a loop over every empty room, each running its own BFS until the first gate appears. That is correct, since BFS from a room finds its nearest gate first. The trouble is repetition. Neighboring rooms run nearly identical searches, and in a grid with few gates each search may scan most of the grid. With R · C cells, the total is O((R · C)²). A second slow variant runs a BFS from each gate and keeps the minimum distance seen per room, which costs O(G · R · C) for G gates and still repeats work when gates are many.

Main approach: one BFS from all gates

Turn the question around. Instead of asking, for each room, where its nearest gate is, ask each gate to flood outward and let the rooms be claimed by whichever flood arrives first. If all gates start in the same queue at distance 0, BFS processes cells in order of distance from the nearest gate. The first time any flood touches a room is therefore the shortest distance from any gate. Once a room has a number, no later arrival can beat it, so it never needs updating again.

  1. Seed the queueScan the grid and push the coordinates of every cell equal to 0.
  2. Pop and expandFor each popped cell, look at its four neighbors.
  3. Claim empty rooms onlyIf a neighbor still holds INF, set it to the popped cell's value plus one and push it. Walls, gates and already-numbered rooms are skipped.
  4. Finish when the queue is emptyRooms that were never claimed keep INF, which is exactly the required output for unreachable rooms.
from collections import deque

EMPTY = 2147483647

def fill_distances(rooms):
    if not rooms:
        return
    rows, cols = len(rooms), len(rooms[0])
    queue = deque((r, c) for r in range(rows) for c in range(cols) if rooms[r][c] == 0)
    while queue:
        r, c = queue.popleft()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == EMPTY:
                rooms[nr][nc] = rooms[r][c] + 1
                queue.append((nr, nc))
Python: multi-source BFS that uses the grid as its own visited marker.
const EMPTY = 2147483647;

function fillDistances(rooms) {
  if (!rooms.length) return;
  const rows = rooms.length, cols = rooms[0].length;
  const queue = [];
  for (let r = 0; r < rows; r++)
    for (let c = 0; c < cols; c++)
      if (rooms[r][c] === 0) queue.push([r, c]);
  for (let head = 0; head < queue.length; head++) {
    const [r, c] = queue[head];
    for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
      if (nr >= 0 && nc >= 0 && nr < rows && nc < cols && rooms[nr][nc] === EMPTY) {
        rooms[nr][nc] = rooms[r][c] + 1;
        queue.push([nr, nc]);
      }
    }
  }
}
JavaScript: same algorithm, with an array and a head index as the queue.

Notice what is missing: no separate visited set and no distance stored in the queue. The grid already says everything. A cell that is not INF has been settled, and its value is its distance. That is a nice point to raise, because it shows you noticed the in-place requirement is a feature, not just a constraint.

Walk through the first example. The queue starts with the gates at (0, 2) and (2, 0). The first wave sets (1, 2) and (1, 0) to 1. The second wave reaches (1, 1) from either side and sets it to 2, and also sets (0, 0) and (2, 2) to 2. Nothing is INF any more, so the remaining pops change nothing.

Complexity

R rows, C columns, G gates
ApproachTimeExtra space
BFS from every roomO((R · C)²)O(R · C) per search
BFS from every gate, keep minimumO(G · R · C)O(R · C) per search
Multi-source BFSO(R · C)O(R · C) for the queue in the worst case
R rows, C columns, G gates. Scroll sideways on a small screen.

Each cell enters the queue at most once, either as a gate at the start or the moment it is claimed, and each pop looks at four neighbors. The queue can hold a large share of the grid when there are many gates, so the extra space is linear, not constant.

Where else this pattern appears

  • Rotting oranges. All rotten cells start in the queue, and the answer is the number of waves needed to reach every fresh cell.
  • Distance to the nearest zero in a binary matrix. Same flood, with zeros as sources and ones as rooms.
  • Nearest hospital or charging station on a map. Real routing adds weights, which turns BFS into multi-source Dijkstra, but the seeding idea is identical.
  • A virtual super source. Imagine one extra node linked to every gate with an edge of length zero. A single BFS from it is the same as seeding all gates, which is a tidy way to justify correctness.

Edge cases to test

  • An empty grid, or a grid with an empty first row.
  • No gates at all: the queue starts empty and every room stays INF.
  • No empty rooms: nothing changes.
  • Rooms enclosed by walls, which must keep INF.
  • A single row or column, where the flood runs in one direction.
  • Many gates next to each other, so rooms between them must take the smaller distance.

Common mistakes

  • Running BFS from one gate at a time and overwriting values without taking a minimum.
  • Using DFS from each gate. DFS reaches rooms by long routes first and needs many corrections.
  • Checking for value greater than 0 instead of equal to INF, which lets the search overwrite rooms that already have a smaller distance.
  • Calling queue.shift() in JavaScript, which makes each pop linear on big grids.
  • Treating gates as rooms and setting them to 1.

How it might sound in the room

Fictional example

Arguing for multi-source BFS
Candidate
If I search from each room I repeat a lot of work. Instead I'll start one BFS from every gate at the same time.
Candidate
BFS handles cells in order of distance, so the first gate wave to reach a room is the nearest one. I write that distance straight into the grid and never revisit the room.
Interviewer
Do you need a visited array?
Candidate
No. A room is unvisited exactly when it still holds the INF sentinel, so the grid tracks that for me. Total work is linear in the number of cells.

The previous problem, Minimum Knight Moves, runs a single-source BFS on a board with no walls at all. The next one, Nearest Exit from Entrance in Maze, reverses this page's setup: one source, many possible targets on the border, and the search stops at the first one it meets. For the queue and grid basics behind both, see the data structure interview questions.

Practicing it with Natively

Natively can read a grid problem from a screenshot during practice and suggest how to seed the search, which is useful as a second opinion after you have tried the flood yourself. It also keeps a transcript of your mock session on your computer, so you can check that you explained why the first claim is the minimum. Read more on the AI interview assistant page.

Questions people ask

How do you solve Walls and Gates?

Put every gate in one queue at distance 0 and run BFS. When the search reaches a room that still holds the empty sentinel, write the current distance plus one into it and push it. Each room is claimed once, by its nearest gate.

Why start BFS from the gates instead of the rooms?

Searching from every room repeats nearly the same work many times, up to O((R · C)²). Starting from all gates together fills the grid in a single O(R · C) pass.

Do you need a separate visited array?

No. A room is unvisited exactly when it still holds 2147483647, so checking for that value does the job and keeps the update in place.

What happens to rooms no gate can reach?

They are never claimed, so they keep the sentinel value, which is the required output.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP