Matrix BFS (breadth-first search on a grid)
medium 18 minMatrix 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?
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.
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 as a node and each allowed move as an edge. With 4-directional movement a cell's neighbours are , , and , 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
Size of the implicit graph
The algorithm
The queue loop on a grid
- 1
Initialise
Put the start in a
dequewith distance 0 and mark it visited now. - 2
Dequeue
Remove the front cell with
popleft(). Cells leave in the order they were found. - 3
Check the goal
If this cell is the target (or an exit), return its distance.
- 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
Repeat
Loop until the queue is empty. Empty without finding the target means it is unreachable: return -1.
Single-source matrix BFS
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))) # -1Correctness
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 0 | col 1 | col 2 | col 3 | col 4 | |
|---|---|---|---|---|---|
| row 0 | S (0) | 1 | 2 | 3 | 4 |
| row 1 | 1 | 2 | 3 | 4 | 5 |
| row 2 | 2 | 3 | 4 | 5 | E (6) |
The queue invariant
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
Mark on enqueue
- Each cell is enqueued once: the queue never exceeds 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
| Movement | Offsets | Open-grid distance | Typical problems |
|---|---|---|---|
| 4 directions | (-1,0) (1,0) (0,-1) (0,1) | Manhattan: | Mazes, rotting oranges, walls and gates, 01 matrix |
| 8 directions | the 4 above plus (-1,-1) (-1,1) (1,-1) (1,1) | Chebyshev: | Shortest path in binary matrix (LeetCode 1091), king moves |
Why diagonals shorten the trip
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]])) # -1Pattern
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
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 movesPattern
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
Why one queue equals k separate searches
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 rotPattern family
Walls and gates, 01 matrix and nearest exit
| Problem | Sources in the queue | Stop when | Answer |
|---|---|---|---|
| Shortest path in binary matrix (1091) | top-left cell | bottom-right dequeued | cells on the path, 8 directions |
| Nearest exit from entrance (1926) | the entrance | first border cell that is not the entrance | steps to that cell |
| Rotting oranges (994) | every rotten orange | fresh count hits 0 | layers processed, or -1 |
| Walls and gates (286) | every gate | queue empty | each room's distance to the nearest gate |
| 01 matrix (542) | every 0 | queue empty | each cell's distance to the nearest 0 |
| As far from land as possible (1162) | every land cell | queue empty | largest distance reached, or -1 |
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]Complexity
O(R·C) time and space
Time: each cell in and out once
Space: visited grid plus the frontier
| Situation | Largest queue | Why |
|---|---|---|
| Single source in a corner, open grid | each layer is one anti-diagonal | |
| Single source in the centre, open grid | each layer is a diamond outline | |
| Long corridor or snake maze | the wave is one cell wide | |
| Multi-source, most cells are sources | the first layer is nearly the whole grid |
Comparison
Matrix BFS versus matrix DFS
| Aspect | Matrix BFS | Matrix DFS |
|---|---|---|
| Data structure | Queue (FIFO) | Stack or recursion (LIFO) |
| Exploration pattern | Level by level, like ripples | One path as deep as it goes, then back up |
| Shortest path, equal costs | Guaranteed | Not guaranteed |
| Best for | Fewest steps, nearest target, spreading over time | Counting islands, connected regions, flood fill, all paths |
| Worst-case memory | : the frontier | : the recursion depth |
| Python gotcha | Use deque, not list.pop(0) | Recursion limit on big grids |
Is this a matrix BFS problem?
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
dirslist changes. - Time is and space is ; store parents if you need the route, and use
deque, neverlist.pop(0).