AlgoViz

Matrix BFS (breadth-first search on a grid)

medium 18 min

Matrix BFS explores a 2D grid in rings of equal distance from the start, using a queue.

See it run

Breadth-first search on a grid: distance layers spread from the source like ripples, with the queue shown under every step.

Operations

BFS flood (distance layers)

Standard BFS on a grid from one start, checking 4 neighbours. Each open cell gets its distance the moment it is discovered, so the numbers grow in layers: 0, then all the 1s, then all the 2s.

Step 1 of 17

A 4 × 4 grid with two walls

0123
0····
1·■··
2····
3··■·

Queue: empty

Walls ■ sit at (1,1) and (3,2). We start at (0,0) and want the distance from it to every open cell. Neighbours are checked right, down, left, up.

Step 1: A 4 × 4 grid with two walls

from collections import dequedef bfs_distances(grid, start):    rows, cols = len(grid), len(grid[0])    dist = [[-1] * cols for _ in range(rows)]   # -1 = not seen yet    dist[start[0]][start[1]] = 0                # mark the start on enqueue    queue = deque([start])    dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]   # right, down, left, up    while queue:        r, c = queue.popleft()        for dr, dc in dirs:            nr, nc = r + dr, c + dc            if (0 <= nr < rows and 0 <= nc < cols                    and grid[nr][nc] != -1 and dist[nr][nc] == -1):                dist[nr][nc] = dist[r][c] + 1   # mark visited NOW                queue.append((nr, nc))    return dist
Time
O(R·C)
Space
O(R·C)
Each cell
enqueued once, dequeued once
Neighbour checks
4 per cell, O(1)

Use the distance grid itself as the visited set: -1 means unseen. Marking it as you enqueue guarantees each cell enters the queue once.

In the real world

The same matrix bfs doing real jobs. Pick one and step through it.

A robot crosses a 5 × 6 floor from the top-left to the bottom-right while two wall segments block the middle. BFS spreads one layer per move until the target lights up.

Step 1 of 11

The floor plan

012345
0S·····
1··■·■·
2··■·■·
3··■···
4·····E

Queue: (0,0)

Walls ■ block column 2 in rows 1 to 3 and column 4 in rows 1 and 2. Start S (0,0), target E (4,5).

Step 1: The floor plan

from collections import dequedef min_steps(grid, start, target):    rows, cols = len(grid), len(grid[0])    seen, queue, steps = {start}, deque([start]), 0    while queue:        for _ in range(len(queue)):       # one layer per pass            r, c = queue.popleft()            if (r, c) == target:                return steps            for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:                nr, nc = r + dr, c + dc                if (0 <= nr < rows and 0 <= nc < cols                        and grid[nr][nc] == 0 and (nr, nc) not in seen):                    seen.add((nr, nc))                    queue.append((nr, nc))        steps += 1    return -1

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Marking visited on dequeue

    critical

    A cell can be discovered by up to four neighbours before it reaches the front. If you only mark it when it is dequeued, each of those neighbours enqueues it again: the queue swells with duplicates and counts (like fresh oranges) go wrong.

    Wrong
    while queue:    r, c = queue.popleft()    visited.add((r, c))            # too late    for nr, nc in neighbours(r, c):        if (nr, nc) not in visited:            queue.append((nr, nc))  # may add the same cell twice
    Right
    visited = {start}while queue:    r, c = queue.popleft()    for nr, nc in neighbours(r, c):        if (nr, nc) not in visited:            visited.add((nr, nc))   # mark on enqueue            queue.append((nr, nc))
  • Indexing before the bounds check

    critical

    Python accepts negative indices, so grid[-1][c] silently reads the last row instead of failing. Checking the value before the bounds lets BFS wrap around the edge of the grid, or crash with IndexError on the far side.

    Wrong
    if grid[nr][nc] == 0 and 0 <= nr < rows and 0 <= nc < cols:    ...
    Right
    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0:    ...   # 'and' short-circuits: bounds first
  • Using list.pop(0) as the queue

    major

    list.pop(0) shifts every remaining item, so each dequeue costs O(queue length). On a big grid the BFS becomes quadratic. collections.deque gives O(1) popleft.

    Wrong
    queue = [start]while queue:    r, c = queue.pop(0)       # O(n) shift
    Right
    from collections import dequequeue = deque([start])while queue:    r, c = queue.popleft()    # O(1)
  • Running one BFS per source

    major

    For rotting oranges, walls and gates or 01 matrix, a separate BFS from each source costs O(k·R·C) and, for spreading problems, simulates the sources one after another instead of together. Put every source in the queue first.

    Wrong
    for gate in gates:    bfs_from(gate, rooms)     # k separate floods
    Right
    queue = deque(gates)          # all sources at distance 0while queue:    ...                       # one flood, O(R·C)
  • Counting minutes per dequeue

    major

    In rotting oranges a minute is one whole layer, not one orange. Incrementing the clock for every popped cell counts oranges. Process len(queue) cells per minute, or store the time with each cell.

    Wrong
    while queue:    r, c = queue.popleft()    minutes += 1              # counts cells, not layers
    Right
    while queue and fresh:    for _ in range(len(queue)):        r, c = queue.popleft()        ...    minutes += 1              # one layer = one minute
  • Using DFS for the shortest path

    minor

    DFS finds a path, not necessarily the shortest, because it commits to one direction until it hits a dead end. To get the minimum with DFS you must explore every path. BFS reaches every cell first by a shortest route.

    Wrong
    def dfs(r, c, steps):    if (r, c) == target:        return steps              # first path found, maybe long    ...
    Right
    while queue:    (r, c), d = queue.popleft()    if (r, c) == target:        return d                  # first arrival is the shortest

Interview tips

  • How to explain it

    • A grid is a graph: each cell is a node and each allowed move is an edge.
    • BFS uses a queue, so cells leave in order of distance: all distance-d cells before any distance-(d + 1) cell.
    • So the first time BFS reaches a cell, it has used the fewest moves. That only holds when every move costs the same.
    • Each cell is enqueued and dequeued at most once: O(R·C) time and O(R·C) space.
  • The template

    • queue = deque([start]); seen = {start} (or a dist grid of -1).
    • while queue: r, c = queue.popleft(); check the goal.
    • for dr, dc in dirs: bounds first, then wall, then seen.
    • Mark, then append. Store the distance with the cell or in the dist grid.
  • Spot the variant

    • Fewest steps, nearest exit, minimum moves: single-source BFS with an early return.
    • Spreading from many places at once (rot, fire, gates, zeros): multi-source BFS.
    • Diagonal moves allowed: add the four diagonal offsets to dirs.
    • Path needed, not just the length: store a parent for every cell.
  • Say these out loud

    • Clarify: 4 or 8 directions? Can I modify the input grid? Is the start itself blocked?
    • Track visited before adding to the queue, not when dequeuing.
    • Weighted cells need Dijkstra; 0/1 weights can use a deque (0-1 BFS).
    • Consider whether you need distances or only reachability; reachability alone can also use DFS.