Sub topic 9
BFS on Grids and Implicit Graphs
This chapter assumes you know the BFS loop from earlier chapters: a deque used as a FIFO queue, vertices marked visited when they are enqueued, and distances that grow one layer at a time. It also assumes you are comfortable with Python lists and tuples.
Many BFS problems never hand you an adjacency list. A maze, a game board, or a puzzle state defines its graph through rules. Such a graph is called an implicit graph: you compute each vertex's neighbors when you need them instead of storing them in advance.
A Grid as a Graph
In a grid, each open cell is a vertex. An edge joins two open cells that share a side, so a cell has up to four neighbors. Blocked cells (# below) and positions outside the grid are not vertices.
The code below builds no graph at all. A list of direction offsets produces candidate neighbors, and each candidate is kept only if it is inside the grid, open, and not yet seen. The dist matrix stores distances and also does the job of the visited set: -1 means "not reached yet" and also "unreachable" once BFS finishes.
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]]Cell (1, 2) is next to the start in a straight line, but its distance is 5. The wall at (1, 1) forces the path down the left side, along the bottom row, and back up. For an R × C grid, BFS runs in O(R·C) time, because each cell has at most four edges.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Indexing the grid before the bounds check | `IndexError`, or Python's negative indices silently wrap to the far side | Put the bounds check first in the `and` chain so it short-circuits |
| Mixing up rows and columns | Wrong answers on grids that are not square | Always use `(row, col)` and index as `grid[r][c]` |
| Marking cells visited when dequeued | The same cell is enqueued many times, which wastes time | Set `dist` when you enqueue the cell |
| Not checking the start cell | A start on a wall gets distance 0 | Check `grid[r0][c0]` before you begin |
Implicit Graphs Beyond Grids
You can use the same pattern on any state space. Pick a hashable value to represent each state, write a rule that produces its neighbors, and keep a dictionary of the states you have seen. The example below finds the fewest operations that turn 1 into a target number, where each operation is either "add 1" or "double". The limit check matters. Without it the state space is infinite, and BFS would never finish when the target cannot be reached.
from collections import deque
def min_steps(start, target):
limit = 2 * target
dist = {start: 0}
queue = deque([start])
while queue:
x = queue.popleft()
if x == target:
return dist[x]
for y in (x + 1, x * 2):
if y <= limit and y not in dist:
dist[y] = dist[x] + 1
queue.append(y)
return None
print(min_steps(1, 10)) # 4 (1 -> 2 -> 4 -> 5 -> 10)Exercise
Run grid_distances on the grid ['...', '.#.', '...'] starting at (0, 0). What is the distance to (2, 2), and how many shortest paths reach it?
Show answer
The distance is 4. There are two shortest paths: right, right, down, down along the top and right edges, or down, down, right, right along the left and bottom edges. The wall at (1, 1) blocks every other route of length 4.
Exercise
In min_steps, what goes wrong if you remove the y not in dist check?
Show answer
Every state can be enqueued many times, once for each way of reaching it. The answer stays correct because the first time BFS dequeues the target it has the smallest distance. But the queue grows exponentially, and if the target is unreachable the function may never return within a practical time.