Sub topic 13
Implicit graphs: grids and computed neighbors
This chapter assumes you can write a breadth-first search over an adjacency list, as in the previous chapter. It also assumes you are comfortable with tuples, dictionaries, sets, and Python generators.
Explicit and implicit graphs
The representations so far are explicit. The program stores the edges in an edge list, a matrix, or an adjacency list. An implicit graph stores no edges. It stores a rule that produces a vertex's neighbors when the algorithm asks for them.
Many problems already have this shape:
- A grid map, where each cell touches the cells next to it.
- A puzzle, where each board position leads to the positions one move away.
- A word ladder, where each word connects to words that differ by one letter.
Building an adjacency list for these would waste memory and time. A 1000 by 1000 grid has a million cells and about four million directed neighbor entries. The rule needs only the grid's dimensions.
A grid as a graph
Treat each cell (row, column) as a vertex. Two cells share an edge when they are adjacent horizontally or vertically. This gives an unweighted, undirected graph.
The neighbor function is the whole representation:
def grid_neighbors(r, c, rows, cols):
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:
yield (nr, nc)
print(list(grid_neighbors(0, 0, 3, 3))) # [(1, 0), (0, 1)]The bounds check drops neighbors that fall off the grid. The corner cell (0, 0) has two neighbors, an edge cell has three, and an interior cell has four.
Cells can also be blocked. You can filter walls inside the neighbor function or at the call site. The next example filters at the call site.
Running BFS on an implicit graph
BFS only needs two things from a graph: the start vertex and a way to list neighbors. It never asks for the whole edge set. So the same algorithm works if you replace graph[node] with a function call.
This version finds the fewest steps from start to goal in a maze. A # marks a wall.
from collections import deque
def grid_neighbors(r, c, rows, cols):
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:
yield (nr, nc)
def shortest_steps(grid, start, goal):
rows, cols = len(grid), len(grid[0])
dist = {start: 0}
queue = deque([start])
while queue:
r, c = queue.popleft()
if (r, c) == goal:
return dist[(r, c)]
for nr, nc in grid_neighbors(r, c, rows, cols):
if grid[nr][nc] != "#" and (nr, nc) not in dist:
dist[(nr, nc)] = dist[(r, c)] + 1
queue.append((nr, nc))
return -1 # goal unreachable
maze = [
"..#.",
".##.",
"....",
]
print(shortest_steps(maze, (0, 0), (0, 3))) # 7The dist dictionary does two jobs. It records the distance from the start, and its keys serve as the seen set. A BFS over an adjacency list used a separate seen set. This version merges the two.
Trade-offs and common errors
An implicit graph costs almost no memory for edges, but each neighbor lookup does a small amount of arithmetic. For grids this is cheaper than a hash lookup. The visited structure still grows with the number of vertices you reach.
Watch for these mistakes:
- Missing bounds checks. Python accepts the index
-1, so a cell at column 0 silently wraps to the last column instead of raising an error. - Marking visited too late. Add a cell to
distwhen you enqueue it, not when you dequeue it. Otherwise the same cell can enter the queue several times. - Lists in a visited set. Lists are unhashable. Use tuples such as
(r, c)as vertex identifiers. - Infinite state spaces. Puzzle graphs can be huge. BFS still works, but you must stop at the goal, as
shortest_stepsdoes.
Exercise
How would you change grid_neighbors so that a cell also connects to its four diagonal neighbors, and how many neighbors does an interior cell then have?
Show answer
Add the four diagonal offsets (1, 1), (1, -1), (-1, 1), and (-1, -1) to the tuple of offsets. The bounds check stays the same. An interior cell then has eight neighbors, and a corner cell has three.