Sub topic 9
BFS on Grids and Implicit Graphs
Earlier chapters stored every graph as an adjacency list, a dictionary that maps each vertex to its neighbors. Many real problems never hand you that dictionary. A maze is a grid of characters. A puzzle is a starting position and a set of legal moves. In both cases the graph exists, but only as a rule for producing neighbors. This chapter shows how to run BFS directly on such graphs without ever building the adjacency list.
This chapter assumes you already know the queue-based BFS loop, why vertices are marked visited when they are enqueued, and why BFS gives shortest distances in unweighted graphs.
What an Implicit Graph Is
An implicit graph is a graph whose vertices and edges are defined by a rule and not stored in memory. To use one you need three things:
- A way to represent a vertex as a hashable value (a tuple, string, or integer) so it can go into a set or dictionary, or a way to index into an array.
- A function that, given a vertex, produces its neighbors.
- A start vertex, and often a goal test.
BFS only ever asks one question of a graph: "what are the neighbors of this vertex?" That is why it works unchanged on implicit graphs. Where the earlier code wrote graph[node], you call a neighbor function or loop over a fixed set of moves.
| Problem | Vertex | Edges (neighbors) |
|---|---|---|
| Maze on a grid | `(row, col)` of an open cell | The 4 adjacent open cells |
| Grid with diagonal moves | `(row, col)` | The 8 surrounding open cells |
| Knight on a chessboard | `(row, col)` | Up to 8 L-shaped jumps that stay on the board |
| Combination lock | String such as `"0000"` | Turn one wheel up or down by one |
| Maze with keys | `(row, col, keys_held)` | Moves that update position and keys |
Grids as Graphs
In a grid, each open cell is a vertex. Two cells share an edge when they are adjacent and both are open. With 4-directional movement, every cell has at most 4 neighbors, so a grid with R rows and C columns has at most R·C vertices and about 2·R·C undirected edges. BFS therefore runs in O(R·C) time and space.
Because the cells are already indexed by row and column, you don't need a dictionary for visited tracking. A 2D list of distances does both jobs. A value of -1 means "not yet reached", and any other value is the BFS distance.
from collections import deque
def grid_distances(grid, start):
rows, cols = len(grid), len(grid[0])
dist = [[-1] * cols for _ in range(rows)]
r0, c0 = start
dist[r0][c0] = 0
queue = deque([start])
while queue:
r, c = queue.popleft()
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 grid[nr][nc] == '.' and dist[nr][nc] == -1):
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
return dist
grid = ['..#',
'.#.',
'...']
print(grid_distances(grid, (0, 0))) # [[0, 1, -1], [1, -1, 5], [2, 3, 4]]Trace the result. The path from (0, 0) goes down the left column, along the bottom row, and up into (1, 2), which takes 5 steps. The cell (0, 2) is a wall, so it stays at -1. The wall at (1, 1) also stays at -1. From the output alone you cannot tell a wall from an open cell that BFS could not reach. If you need that difference, check grid[r][c] as well.
The Neighbor Filter
Every candidate neighbor passes through the same checks, in a fixed order. The order matters. The bounds check has to come first, because Python's and stops at the first false condition. If nr is -1, the expression grid[-1][nc] would not raise an error. It would quietly read the last row, which is a hard bug to find.
Common Grid Mistakes
- Swapping rows and columns.
grid[r][c]indexes the row first. If you think in(x, y), thenxis the column, and writinggrid[x][y]reads the wrong cell or goes out of range on grids that aren't square. - Relying on negative indices. As noted above, Python accepts
grid[-1]. Always check0 <= nrexplicitly. - Marking visited when dequeued. On a grid each cell can be reached from up to 4 neighbors. If you mark cells only when you dequeue them, the same cell can enter the queue several times. The distances may still come out right, but the work grows, and on large grids the queue can blow up.
- Forgetting that the start may be blocked. If the start cell is a wall, decide what that means for your problem and handle it before the loop.
- Building a set of tuples for huge grids. A
setof(r, c)tuples is correct but uses far more memory than a 2D list of integers. For a 2000×2000 grid, that difference matters.
General State-Space Search
Grids are one kind of implicit graph. More generally, a vertex can be any state of a puzzle or system, and an edge is a single legal move. BFS then finds the minimum number of moves from one state to another.
A generic version takes the neighbor rule as a function:
from collections import deque
def bfs_distance(start, goal, neighbors):
dist = {start: 0}
queue = deque([start])
while queue:
state = queue.popleft()
if state == goal:
return dist[state]
for nxt in neighbors(state):
if nxt not in dist:
dist[nxt] = dist[state] + 1
queue.append(nxt)
return -1
KNIGHT = [(1, 2), (2, 1), (-1, 2), (-2, 1),
(1, -2), (2, -1), (-1, -2), (-2, -1)]
def knight_moves(n):
def neighbors(pos):
r, c = pos
for dr, dc in KNIGHT:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n:
yield (nr, nc)
return neighbors
print(bfs_distance((0, 0), (7, 7), knight_moves(8))) # 6The neighbor function is a generator. It yields states one at a time, so no list of edges is ever built. Here dist is a dictionary because states are not necessarily small integers.
A Combination Lock
A lock has four wheels, each showing a digit from 0 to 9. One move turns a single wheel up or down by one, and 9 wraps around to 0. Some combinations are dead ends: if the lock reaches one, it jams. What is the fewest number of moves from "0000" to the target?
Each state is a 4-character string, and each state has exactly 8 neighbors. The state space has 10,000 vertices, which BFS handles instantly.
from collections import deque
def open_lock(deadends, target):
dead = set(deadends)
start = '0000'
if start in dead:
return -1
dist = {start: 0}
queue = deque([start])
while queue:
state = queue.popleft()
if state == target:
return dist[state]
for i in range(4):
digit = int(state[i])
for step in (1, -1):
new_digit = (digit + step) % 10
nxt = state[:i] + str(new_digit) + state[i + 1:]
if nxt not in dead and nxt not in dist:
dist[nxt] = dist[state] + 1
queue.append(nxt)
return -1
print(open_lock(['0201', '0101', '0102', '1212', '2002'], '0202')) # 6
print(open_lock(['8888'], '0009')) # 1In the second call the wrap-around is what makes the answer 1. Turning the last wheel down from 0 gives 9 in one move.
Dead ends act like walls: the code never enqueues them. Putting them in a separate set keeps "blocked" apart from "visited". If you merged the two by pre-loading dead ends into dist, you would have to give them a fake distance, and that is easy to misread later.
Adding Information to the State
Sometimes position alone does not capture everything that affects future moves. Suppose a maze has a door that opens only if you have picked up a key. Arriving at cell (3, 4) with the key is a different situation from arriving there without it. Treating the two as one vertex makes BFS wrong: whichever arrival comes first claims the cell, and the other is discarded even though it may be the only one that can go through the door.
The fix is to put the extra information into the vertex: (row, col, has_key). The graph now has twice as many vertices, and BFS treats each combination separately. With k independent keys, you can store the keys held as a bitmask, and the state space grows to R·C·2^k.
The rule for choosing a state is: two situations can share a vertex only if every possible future from them is the same. If any future move depends on a piece of information, that information belongs in the state.
Choosing a Visited Structure
| Vertex type | Visited / distance structure | Notes |
|---|---|---|
| Grid cell `(r, c)` | 2D list initialized to `-1` | Fastest and most compact |
| Grid cell plus small flags | 3D list, `dist[r][c][mask]` | Works while the mask range is small |
| Strings, tuples, arbitrary states | `dict` mapping state to distance | Flexible; states must be hashable |
| Very large integer-coded states | `bytearray` or array indexed by code | Saves memory when states map to dense integers |
Lists cannot go into a set or be dictionary keys. If your state is naturally a list, such as a board layout, convert it to a tuple or a string before you store it.
Exercise
Using grid_distances, what is the distance to every cell for the grid ['...', '.#.', '...'] starting at (0, 0)? Which cell is farthest, and why are there two shortest routes to it?
Show answer
The result is [[0, 1, 2], [1, -1, 3], [2, 3, 4]]. The farthest open cell is (2, 2) at distance 4. The wall in the center blocks the middle, so you can reach (2, 2) either along the top row and down the right column or down the left column and along the bottom row. Both routes take 4 steps.
Exercise
On an 8×8 board, what does bfs_distance((0, 0), (1, 1), knight_moves(8)) return, and why isn't the answer 2 as it would be on an unbounded board?
Show answer
It returns 4. A knight changes square color on every move, and (0, 0) and (1, 1) have the same color, so the answer must be even. On an unbounded board, (0, 0) -> (2, -1) -> (1, 1) takes 2 moves, but (2, -1) is off the board. From the corner the only first moves are (1, 2) and (2, 1), and neither is a knight move away from (1, 1), so 2 is impossible. A 4-move route exists: (0, 0) -> (1, 2) -> (2, 4) -> (0, 3) -> (1, 1).
Exercise
A maze has walls, open cells, and one door 'D' that you can pass only after stepping on the key cell 'K'. A student runs grid BFS with vertex (row, col) and lets the search pass 'D' whenever the current path has visited 'K'. Why can this return the wrong answer, and what should the vertex be?
Show answer
The visited marker is per cell, so the first arrival at a cell claims it. If BFS reaches a cell without the key first, a later arrival with the key gets discarded, and the door may never be crossed, even though a valid route exists. The vertex should be (row, col, has_key), with a 3D distance array or a dictionary keyed by that tuple. Then arrivals with and without the key are tracked separately.