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.

Video lesson · Chapter 1 of 5

How many moves to the exit?

0:00 / 4:51

Matrix breadth-first search — Eight moves to the exit

1:05Reel

Read caption

Rafi finds the shortest path across a roller rink with a blocked aisle. Watch the queue spread in waves, then follow the parent trail. One ring, one move. First arrival gives the fewest moves.

How it works

Step through the idea, or press Play.

Step 1 of 3

Seed the queue. Put the start (or every source) in the queue at distance 0 and mark it visited

Understand it

Start here

What matrix BFS is

Matrix BFS is breadth-first search on a 2D grid. It explores the grid level by level, like ripples spreading from a stone dropped in water: every cell one move away first, then every cell two moves away, and so on. The engine is a queue, exactly as in tree BFS; the only new parts are the four (or eight) directions and a visited grid.

  • Shortest path

    The fewest moves between two cells of an unweighted grid, such as a maze or a binary matrix.

  • Multi-source spreading

    Rotting oranges, fire, flood water: many starting cells spreading at once, one layer per minute.

  • Nearest target

    The closest exit, gate or zero from every cell, found in a single pass.

The model

A grid is a graph

Treat each cell (r,c)(r, c) as a node and each allowed move as an edge. With 4-directional movement a cell's neighbours are (r−1,c)(r-1, c), (r+1,c)(r+1, c), (r,c−1)(r, c-1) and (r,c+1)(r, c+1), as long as they are inside the grid and not walls. You never build the graph: the neighbours come from adding a direction offset. See graphs for the general picture.

One cell and its four neighbours

Every neighbour goes through the same three checks: bounds, wall, already seen.

Size of the implicit graph

V=R⋅C,E≤2RC  (4 directions),E≤4RC  (8 directions)V = R \cdot C, \qquad E \le 2RC \;(\text{4 directions}), \qquad E \le 4RC \;(\text{8 directions})
An R×CR \times C grid has RCRC nodes. Each cell has at most 4 (or 8) neighbours and every edge is shared by two cells, so E=O(RC)E = O(RC) and graph BFS's O(V+E)O(V + E) becomes O(R⋅C)O(R \cdot C).

The algorithm

The queue loop on a grid

  1. 1

    Initialise

    Put the start in a deque with distance 0 and mark it visited now.

  2. 2

    Dequeue

    Remove the front cell with popleft(). Cells leave in the order they were found.

  3. 3

    Check the goal

    If this cell is the target (or an exit), return its distance.

  4. 4

    Explore

    For each direction, compute the neighbour. If it is in bounds, open and unseen, mark it and enqueue it with distance + 1.

  5. 5

    Repeat

    Loop until the queue is empty. Empty without finding the target means it is unreachable: return -1.

Single-source matrix BFS

Five moves in a loop: initialise, dequeue, check the goal, explore, repeat.
Python
from collections import dequedef shortest_path(grid, start, target):    rows, cols = len(grid), len(grid[0])    queue = deque([(start[0], start[1], 0)])   # (row, col, distance)    visited = {start}    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]    while queue:        row, col, dist = queue.popleft()        if (row, col) == target:            return dist        for dr, dc in directions:            nr, nc = row + dr, col + dc            if (0 <= nr < rows and 0 <= nc < cols                    and (nr, nc) not in visited and grid[nr][nc] == 1):                visited.add((nr, nc))                queue.append((nr, nc, dist + 1))    return -1   # target not reachablegrid = [    [1, 1, 1, 1, 1],    [1, 0, 0, 1, 1],    [1, 1, 1, 1, 1],    [1, 1, 0, 0, 1],    [1, 1, 1, 1, 1],]print(shortest_path(grid, (0, 0), (4, 4)))   # 8print(shortest_path([[1, 0], [0, 1]], (0, 0), (1, 1)))   # -1
The standard template on a 5 × 5 grid (1 = open, 0 = blocked). The answer is 8.
Edit and run it in your browser

Correctness

Why BFS gives shortest paths

Number every cell by the move on which BFS discovers it. On an open 3 × 5 grid from S in the top-left, the numbers form diagonal bands: all the 1s, then all the 2s. The target E gets 6, which is the length of the shortest path.

Discovery distance from S, 4 directions

col 0col 1col 2col 3col 4
row 0S (0)1234
row 112345
row 22345E (6)
Every distance-1 cell is visited before any distance-2 cell. The first time E is reached, the path has 6 moves, and no shorter path exists.

The queue invariant

queue=[ d,…,d⏟front, d+1,…,d+1⏟rear ]⟹dist(v)=dist(u)+1=δ(s,v)\text{queue} = [\,\underbrace{d, \dots, d}_{\text{front}},\ \underbrace{d+1, \dots, d+1}_{\text{rear}}\,] \quad\Longrightarrow\quad \text{dist}(v) = \text{dist}(u) + 1 = \delta(s, v)
At any moment the queue holds at most two distances, dd then d+1d + 1. Dequeuing a distance-dd cell only adds distance-(d+1)(d+1) cells at the rear. By induction, each cell is first reached from a neighbour uu at the true shortest distance δ(s,u)\delta(s, u), so its own label equals δ(s,v)\delta(s, v). If a shorter route existed, vv would have been discovered in an earlier layer.

The core trick

Mark visited on enqueue

A cell can be discovered by up to four neighbours before it reaches the front of the queue. Mark it the moment you enqueue it, and seed the visited set with the start before the loop. Then each cell enters the queue exactly once.

Where the mark goes

Marking on enqueue closes the gap between discovery and processing, so no second neighbour can add the same cell.

Mark on enqueue

  • Each cell is enqueued once: the queue never exceeds R⋅CR \cdot C entries.
  • Counts such as fresh oranges stay correct.
  • A dist grid of -1 values can be the visited set: one array, two jobs.

Mark on dequeue

  • The same cell can be enqueued by several neighbours.
  • The queue swells with duplicates and the work grows.
  • Decrement-style counters go negative or finish early.

Moves

4 versus 8 directions

MovementOffsetsOpen-grid distanceTypical problems
4 directions(-1,0) (1,0) (0,-1) (0,1)Manhattan: ∣Δr∣+∣Δc∣|\Delta r| + |\Delta c|Mazes, rotting oranges, walls and gates, 01 matrix
8 directionsthe 4 above plus (-1,-1) (-1,1) (1,-1) (1,1)Chebyshev: max⁡(∣Δr∣,∣Δc∣)\max(|\Delta r|, |\Delta c|)Shortest path in binary matrix (LeetCode 1091), king moves
On the open 3 × 5 grid above, S to E is 6 moves with 4 directions and 4 moves with 8.

Why diagonals shorten the trip

d4=∣Δr∣+∣Δc∣=2+4=6,d8=max⁡(∣Δr∣,∣Δc∣)=max⁡(2,4)=4d_4 = |\Delta r| + |\Delta c| = 2 + 4 = 6, \qquad d_8 = \max(|\Delta r|, |\Delta c|) = \max(2, 4) = 4
A diagonal step changes the row and the column at once, so min⁡(∣Δr∣,∣Δc∣)\min(|\Delta r|, |\Delta c|) pairs of moves collapse into single moves. Walls can only make both numbers larger.
Python
from collections import dequeDIRS8 = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]def shortest_clear_path(grid):    n = len(grid)    if grid[0][0] or grid[n - 1][n - 1]:        return -1                      # blocked start or end    queue = deque([(0, 0, 1)])         # (row, col, cells so far)    grid[0][0] = 1                     # mark by overwriting    while queue:        r, c, length = queue.popleft()        if (r, c) == (n - 1, n - 1):            return length        for dr, dc in DIRS8:            nr, nc = r + dr, c + dc            if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0:                grid[nr][nc] = 1                queue.append((nr, nc, length + 1))    return -1print(shortest_clear_path([[0, 1], [1, 0]]))                     # 2: one diagonal stepprint(shortest_clear_path([[0, 0, 0], [1, 1, 0], [1, 1, 0]]))    # 4print(shortest_clear_path([[1, 0], [0, 0]]))                     # -1
LeetCode 1091 style: 0 is clear, 1 is blocked, 8 directions, the answer counts cells on the path.
Edit and run it in your browser

Pattern

Shortest path and the route itself

When the question wants the route, not just its length, store a parent for every cell at the moment you mark it: the cell that discovered it. When the target is dequeued, follow parents back to the start and reverse. The parent map doubles as the visited set.

Rebuilding the path from breadcrumbs

Each lookup is O(1), so the rebuild costs O(path length) on top of the BFS.
Python
from collections import dequedef shortest_route(grid, start, target):    rows, cols = len(grid), len(grid[0])    parent = {start: None}            # visited set + breadcrumbs    queue = deque([start])    while queue:        r, c = queue.popleft()        if (r, c) == target:            path, cur = [], target            while cur is not None:                path.append(cur)                cur = parent[cur]            return path[::-1]        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] != -1 and (nr, nc) not in parent):                parent[(nr, nc)] = (r, c)                queue.append((nr, nc))    return Nonegrid = [[0, 0, 0], [0, -1, 0], [0, 0, 0]]print(shortest_route(grid, (0, 0), (2, 2)))# [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]: 4 moves
3 × 3 grid with a wall in the middle (-1). The route goes along the top and down the right side.
Edit and run it in your browser

Pattern

Multi-source BFS

When many cells spread at the same time (every rotten orange, every gate, every zero), put all of them in the queue at distance 0 before the loop. Everything after that is the ordinary loop. Each cell is claimed by whichever source's wave reaches it first, which is its nearest source.

Rotting oranges, one layer per minute

One pass of the inner loop drains exactly one layer, which is one minute.

Why one queue equals k separate searches

dist(v)=min⁡s∈Sδ(s,v)=δ(s∗,v),s∗ a virtual source joined to every s∈S by a 0-cost edge\text{dist}(v) = \min_{s \in S} \delta(s, v) = \delta(s^{*}, v), \qquad s^{*} \text{ a virtual source joined to every } s \in S \text{ by a 0-cost edge}
Seeding all kk sources is the same as one BFS from an imaginary super source. The cost stays O(R⋅C)O(R \cdot C) instead of O(k⋅R⋅C)O(k \cdot R \cdot C) for kk separate searches.
Python
from collections import dequedef oranges_rotting(grid):    rows, cols = len(grid), len(grid[0])    queue, fresh = deque(), 0    for r in range(rows):        for c in range(cols):            if grid[r][c] == 2:                queue.append((r, c))            elif grid[r][c] == 1:                fresh += 1    minutes = 0    while queue and fresh > 0:        for _ in range(len(queue)):            # one minute            r, c = queue.popleft()            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] == 1:                    grid[nr][nc] = 2           # rot now = mark on enqueue                    fresh -= 1                    queue.append((nr, nc))        minutes += 1    return minutes if fresh == 0 else -1print(oranges_rotting([[2, 1, 1], [1, 1, 0], [0, 1, 1]]))   # 4print(oranges_rotting([[2, 1, 1], [0, 1, 1], [1, 0, 1]]))   # -1: (2,0) is cut offprint(oranges_rotting([[0, 2]]))                            # 0: nothing to rot
Rotting oranges: 2 rotten, 1 fresh, 0 empty.
Edit and run it in your browser

Pattern family

Walls and gates, 01 matrix and nearest exit

ProblemSources in the queueStop whenAnswer
Shortest path in binary matrix (1091)top-left cellbottom-right dequeuedcells on the path, 8 directions
Nearest exit from entrance (1926)the entrancefirst border cell that is not the entrancesteps to that cell
Rotting oranges (994)every rotten orangefresh count hits 0layers processed, or -1
Walls and gates (286)every gatequeue emptyeach room's distance to the nearest gate
01 matrix (542)every 0queue emptyeach cell's distance to the nearest 0
As far from land as possible (1162)every land cellqueue emptylargest distance reached, or -1
Six problems, one loop. Only the seeding, the stop test and what you return change.
Python
from collections import dequeINF = 2 ** 31 - 1def walls_and_gates(rooms):    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 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 rooms[nr][nc] == INF:                rooms[nr][nc] = rooms[r][c] + 1                queue.append((nr, nc))rooms = [[INF, -1, 0, INF], [INF, INF, INF, -1], [INF, -1, INF, -1], [0, -1, INF, INF]]walls_and_gates(rooms)for row in rooms:    print(row)# [3, -1, 0, 1] / [2, 2, 1, -1] / [1, -1, 2, -1] / [0, -1, 3, 4]
Walls and gates: -1 wall, 0 gate, INF empty room. INF doubles as the unvisited flag.
Edit and run it in your browser

Complexity

O(R·C) time and space

Time: each cell in and out once

T(R,C)=∑cells(1⏟enqueue+1⏟dequeue+k⏟neighbour checks)=(2+k)⋅RC=O(R⋅C)T(R, C) = \sum_{\text{cells}} \big(\underbrace{1}_{\text{enqueue}} + \underbrace{1}_{\text{dequeue}} + \underbrace{k}_{\text{neighbour checks}}\big) = (2 + k) \cdot RC = O(R \cdot C)
With marking on enqueue each cell enters the queue at most once and checks k=4k = 4 or k=8k = 8 neighbours, each in O(1)O(1). The constant does not change the order.

Space: visited grid plus the frontier

S(R,C)=O(R⋅C)⏟visited or dist+O(frontier)⏟queue,frontier≤R⋅CS(R, C) = \underbrace{O(R \cdot C)}_{\text{visited or dist}} + \underbrace{O(\text{frontier})}_{\text{queue}}, \qquad \text{frontier} \le R \cdot C
The visited structure is always O(R⋅C)O(R \cdot C). The queue holds about one layer: from a corner of an open grid that is a diagonal of at most min⁡(R,C)\min(R, C) cells, but with many sources (all cells rotten, all zeros) it can start with almost every cell in it.
SituationLargest queueWhy
Single source in a corner, open grid≈min⁡(R,C)\approx \min(R, C)each layer is one anti-diagonal
Single source in the centre, open gridO(R+C)O(R + C)each layer is a diamond outline
Long corridor or snake mazeO(1)O(1)the wave is one cell wide
Multi-source, most cells are sourcesO(R⋅C)O(R \cdot C)the first layer is nearly the whole grid
Time is always O(R⋅C)O(R \cdot C); the queue size depends on the shape of the wave.

Comparison

Matrix BFS versus matrix DFS

AspectMatrix BFSMatrix DFS
Data structureQueue (FIFO)Stack or recursion (LIFO)
Exploration patternLevel by level, like ripplesOne path as deep as it goes, then back up
Shortest path, equal costsGuaranteedNot guaranteed
Best forFewest steps, nearest target, spreading over timeCounting islands, connected regions, flood fill, all paths
Worst-case memoryO(R⋅C)O(R \cdot C): the frontierO(R⋅C)O(R \cdot C): the recursion depth
Python gotchaUse deque, not list.pop(0)Recursion limit on big grids
For pure reachability or counting regions, both work; matrix DFS is often shorter to write. Reach for BFS the moment distance or time matters.

Is this a matrix BFS problem?

Distance or time on a grid with equal-cost moves is the BFS signal.

Wrap-up

Key takeaways

Key points

  • A grid is a graph: cells are nodes, allowed moves are edges, and neighbours come from direction offsets.
  • BFS uses a queue, so cells leave in distance order; the first time a cell is reached is by a shortest route, as long as every move costs the same.
  • Mark a cell visited when you enqueue it, and check bounds before reading the grid.
  • Multi-source BFS seeds every source at distance 0; one pass of for _ in range(len(queue)) is one minute or one layer.
  • Four directions give Manhattan distance, eight give Chebyshev distance; only the dirs list changes.
  • Time is O(R⋅C)O(R \cdot C) and space is O(R⋅C)O(R \cdot C); store parents if you need the route, and use deque, never list.pop(0).

Sources