Sub topic 1
Framing Pathfinding as Graph Search
Before you can run A, you have to say exactly what you are searching. "Find a route from here to there" is too vague for an algorithm. This chapter turns pathfinding problems into weighted graphs with a precise interface. Every later chapter builds on that interface: uniform-cost search, greedy search, A, and its variants all consume the same thing.
Prerequisites
This chapter assumes you can already:
- Read and write basic Python, including functions, generators (
yield), tuples, and dictionaries. - Describe a graph in terms of nodes, edges, and edge weights.
- Trace breadth-first search (BFS) with a queue.
- Recognize a priority queue or binary heap. This chapter doesn't use one, but the next ones do.
- Read Big-O statements such as O(b^d).
The Parts of a Search Problem
A search problem has a small set of parts. Once you can name each part for your problem, the choice of algorithm becomes a separate question.
| Component | Meaning | Grid example |
|---|---|---|
| State | A complete description of the situation that matters for future moves | A cell `(row, col)` |
| Start state | Where the search begins | `(0, 0)` |
| Goal test | A check that says whether a state is a goal | `cell == (2, 3)` |
| Actions / successors | The states reachable in one step from a given state | The open neighboring cells |
| Step cost | A non-negative cost for each transition | 1 per move, or terrain cost |
| Path cost | The sum of step costs along a path | Total distance travelled |
A solution is a sequence of states from the start to a goal. An optimal solution is a solution with the lowest path cost. The algorithms in this tutorial differ in how they order their exploration and whether they guarantee optimality.
States are graph nodes, transitions are edges
If you treat each state as a node and each transition as a directed edge weighted by its step cost, you get a state-space graph. Pathfinding then becomes a search for the least-cost path in a weighted graph. Edges are directed in general. On a grid they usually come in symmetric pairs, but one-way doors, slopes that cost more uphill, and conveyor belts all break that symmetry.
Implicit Graphs: The Neighbors Function
You rarely build the whole graph up front. A 1000×1000 grid has a million nodes, and the state space of a sliding-tile puzzle has billions. Search algorithms instead work on an implicit graph: a function that, given a state, generates its successors when asked.
This tutorial uses one interface throughout:
def neighbors(state):
"""Yield (next_state, step_cost) pairs for every legal move from state."""
...The state must be hashable, because the algorithms store states in dictionaries and sets. Tuples, strings, integers, and frozensets work. Lists and dicts do not.
Here is a small explicit graph wrapped in that interface:
graph = {
'S': [('A', 1), ('B', 4)],
'A': [('B', 2), ('G', 6)],
'B': [('G', 1)],
'G': [],
}
def graph_neighbors(node):
yield from graph[node]
print(list(graph_neighbors('S'))) # [('A', 1), ('B', 4)]Grids as Graphs
Grid maps are the most common pathfinding setting. Each passable cell is a node. Which cells count as neighbors depends on the movement model:
| Movement model | Neighbors per cell | Typical step costs |
|---|---|---|
| 4-connected | Up, down, left, right | 1 per move |
| 8-connected, diagonal cost √2 | Adds the four diagonals | 1 orthogonal, √2 diagonal |
| 8-connected, diagonal cost 1 | Adds the four diagonals | 1 for every move |
| Weighted terrain | Any of the above | Cost depends on the cell entered |
The movement model is part of the problem definition. You choose it before you pick a heuristic. Chapter 10 shows that the right heuristic follows directly from this choice.
Here is an 8-connected grid with diagonal cost √2. It forbids "corner cutting", meaning a diagonal move between two walls:
import math
def grid8_neighbors(grid):
rows, cols = len(grid), len(grid[0])
def open_cell(r, c):
return 0 <= r < rows and 0 <= c < cols and grid[r][c] == '.'
def neighbors(cell):
r, c = cell
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
nr, nc = r + dr, c + dc
if not open_cell(nr, nc):
continue
if dr != 0 and dc != 0:
# Disallow squeezing diagonally past a blocked corner.
if not (open_cell(r + dr, c) and open_cell(r, c + dc)):
continue
yield (nr, nc), math.sqrt(2)
else:
yield (nr, nc), 1
return neighbors
grid = ["...",
".#.",
"..."]
n = grid8_neighbors(grid)
print(sorted(n((0, 0)))) # [((0, 1), 1), ((1, 0), 1)]Cell (0, 0) has no diagonal move to (1, 1) because that cell is a wall.
Why BFS Is Not Enough
BFS finds the path with the fewest edges. That is the least-cost path only when every step costs the same. On the graph above, BFS returns a path, but it isn't the cheapest one:
from collections import deque
graph = {
'S': [('A', 1), ('B', 4)],
'A': [('B', 2), ('G', 6)],
'B': [('G', 1)],
'G': [],
}
def graph_neighbors(node):
yield from graph[node]
def bfs(start, goal, neighbors):
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]
for nxt, _cost in neighbors(node):
if nxt not in parent:
parent[nxt] = node
queue.append(nxt)
return None
def path_cost(path, neighbors):
total = 0
for a, b in zip(path, path[1:]):
total += dict(neighbors(a))[b]
return total
path = bfs('S', 'G', graph_neighbors)
print(path, path_cost(path, graph_neighbors)) # ['S', 'A', 'G'] 7
print(path_cost(['S', 'A', 'B', 'G'], graph_neighbors)) # 4BFS ignores the weights, so it accepts the two-edge path costing 7 and misses the three-edge path costing 4. Fixing this means ordering exploration by accumulated cost, which is what uniform-cost search does in the next chapter.
Choosing the State: The Most Common Modeling Error
The state must include everything that affects which moves are legal or what they cost later. If it leaves something out, two different situations get merged into one node. The search then throws away one of them and can return wrong answers or no answer.
Typical things that belong in the state besides position:
- Keys collected or switches toggled, when doors depend on them.
- Facing direction, when turning costs time (robots, vehicles).
- Remaining fuel or battery, when it limits further moves.
- Time step, when obstacles move.
Here is a grid where the door D opens only after you pick up the key k. Position alone is not enough. You may need to visit the same cell twice, once without the key and once with it.
def key_door_neighbors(grid):
rows, cols = len(grid), len(grid[0])
def neighbors(state):
r, c, has_key = state
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue
ch = grid[nr][nc]
if ch == '#' or (ch == 'D' and not has_key):
continue
yield (nr, nc, has_key or ch == 'k'), 1
return neighbors
grid = ["k.D.",
"##.#"]
n = key_door_neighbors(grid)
print(list(n((0, 1, False)))) # [((0, 0, True), 1)]
print(list(n((0, 1, True)))) # [((0, 2, True), 1), ((0, 0, True), 1)]There is a cost to this. Adding a boolean doubles the state space, and adding k independent keys multiplies it by 2^k. Model only what matters.
Size and Branching
Two numbers describe how hard a search problem is:
- Branching factor b is the average number of successors per state: about 4 on a 4-connected grid and about 8 on an 8-connected one.
- Solution depth d is the number of steps in the shallowest goal.
An uninformed search can expand on the order of O(b^d) states. On a grid the state space is bounded by the number of cells, so the practical limit is the map area. In puzzle domains the exponential term dominates. Later chapters measure how well a heuristic cuts this down.
Exercise
A robot on a 4-connected grid can move forward one cell (cost 1) or rotate 90 degrees in place (cost 1). Why is (row, col) an incorrect state, and what should the state be?
Show answer
The legal forward move and the cost of reaching a neighbor depend on which way the robot faces, so two visits to the same cell with different headings are different situations. If the state is only (row, col), the search merges them and may discard the cheaper one. The state should be (row, col, heading) with heading in {N, E, S, W}. That makes four times as many states, and rotation becomes an edge between states that share a cell.
Exercise
In the weighted graph from this chapter, change the edge A -> G to cost 2. Which path does BFS return now, and is it optimal?
Show answer
BFS still returns ['S', 'A', 'G'] because it expands by edge count and finds G through A first. Its cost is now 1 + 2 = 3, which is less than S-A-B-G at 4 and S-B-G at 5, so here it happens to be optimal. That is luck: BFS never looked at the weights.