Sub topic 3
Turning a Grid into a Graph
This chapter assumes you know Python lists, tuples, sets, and dictionaries, and that you have met the idea of a graph (vertices joined by edges). Here we map a grid onto that idea and check the mapping by building a graph from a small map.
Cells become vertices
A grid is a list of rows. Each open cell is a vertex. The natural name for a vertex is its coordinate pair (r, c): row first, then column. A tuple is hashable, so it works as a dictionary key or set member.
Walls are not vertices. A cell marked # is simply left out of the graph.
Moves become edges
Two cells share an edge when a single move takes you from one to the other. With 4-direction movement, each cell connects to its up, down, left, and right neighbours. With 8-direction movement, it also connects to its four diagonal neighbours.
Moves on a plain grid are reversible, so every edge is undirected. If you can step from A to B, you can step from B to A. Directed edges appear when a rule breaks this symmetry, such as one-way tiles.
The edges also have a weight. On a plain grid every move counts as one step, so all weights are equal. Later chapters cover grids where entering a cell has a cost.
Building the explicit graph once
You do not need to build the graph ahead of time, and a later chapter shows how to skip that. Building it once is still useful for seeing the mapping. This code turns a grid into an adjacency list using the same neighbour rules as the chapter's neighbors function.
def neighbors(grid, r, c, diagonal=False):
steps = [(-1, 0), (1, 0), (0, -1), (0, 1)]
if diagonal:
steps += [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for dr, dc in steps:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != '#':
yield nr, nc
def grid_to_graph(grid, diagonal=False):
graph = {}
for r, row in enumerate(grid):
for c, ch in enumerate(row):
if ch != '#':
graph[(r, c)] = list(neighbors(grid, r, c, diagonal))
return graph
grid = [
"...",
".#.",
"...",
]
graph = grid_to_graph(grid)
print(len(graph))
print(graph[(0, 0)])
print(graph[(2, 1)])The output is:
8
[(1, 0), (0, 1)]
[(1, 1)...Do not trust that last line. Trace it by hand instead. Cell (2, 1) has the wall (1, 1) above it, so its neighbours are (2, 0) and (2, 2) only. The program prints [(2, 0), (2, 2)], because the steps are tried in the order up, down, left, right and the wall is skipped.
For (0, 0) the order is up (out of bounds), down (1, 0), left (out of bounds), right (0, 1). That gives [(1, 0), (0, 1)].
Common mistakes
- Using
grid[r][c]with(x, y)thinking. Pick row-column order and keep it everywhere. - Letting negative indexes through. Python accepts
grid[-1], so the check0 <= nris required. - Treating
#as a vertex with no edges. It still appears in the graph and inflates counts.
Exercise
How many vertices and how many undirected edges does the 3 by 3 grid with a wall in the centre have under 4-direction movement?
Show answer
It has 8 vertices, because the wall cell is excluded. It has 8 edges: the 8 open cells form a ring around the wall, and each cell touches exactly its two ring neighbours.