Sub topic 1
Framing Pathfinding as Graph Search
Before A* can find a path, the problem has to be described in a form a search algorithm can work with. This chapter shows how to turn a map, a puzzle, or a road network into a weighted graph with a start node and a goal. Every later chapter uses this framing.
Prerequisites
This chapter assumes you can read basic Python. It also assumes you know what graph nodes, edges, and edge weights are, and that you have seen breadth-first search. Priority queues and Big-O notation come up in later chapters, not in this one.
The Parts of a Search Problem
A search problem has five parts:
| Part | Meaning | Grid example |
|---|---|---|
| State | A distinct situation the agent can be in | A cell `(row, col)` |
| Start state | Where the search begins | `(0, 0)` |
| Goal test | Checks whether a state is a goal | `cell == (2, 3)` |
| Successors | The states reachable in one move, each with a step cost | Open adjacent cells, cost 1 |
| Path cost | The sum of step costs along a path | Number of moves |
Each state is a node, and each move is a directed edge whose weight is the step cost. A solution is a path from the start to a goal. An optimal solution is a path with the lowest total cost.
Explicit and Implicit Graphs
A small graph can be stored explicitly, as an adjacency list. Most real search spaces are too large for that. A puzzle can have billions of states, and a game map changes while the game runs. In those cases the graph is implicit: you never build it, and you generate successors on demand with a function.
The rest of this tutorial uses one interface for both cases. neighbors(state) yields (next_state, cost) pairs.
graph = {
"S": [("A", 1), ("B", 2)],
"A": [("G", 5), ("B", 1)],
"B": [("G", 2)],
"G": [],
}
def explicit_neighbors(state):
return iter(graph[state])
def path_cost(path, neighbors):
total = 0
for a, b in zip(path, path[1:]):
total += dict(neighbors(a))[b]
return total
print(path_cost(["S", "A", "G"], explicit_neighbors)) # 6
print(path_cost(["S", "B", "G"], explicit_neighbors)) # 4A grid version would compute neighbors from coordinates and skip walls and out-of-bounds cells. Because the interface stays the same, the search code does not need to know which kind of graph it is working on.
Common Errors
- Unhashable states. Search algorithms keep states in dicts and sets. Use tuples, not lists, for coordinates or puzzle boards.
- Too little in the state. If the cost of a move depends on something like facing direction or keys collected, that information must be part of the state. Otherwise two different situations get merged into one node.
- Negative step costs. Uniform-cost search and A* assume every step cost is zero or more. A negative edge breaks their guarantees.
- Confusing step count with cost. Breadth-first search minimizes the number of edges. When edges have different weights, the path with the fewest moves can cost more, as the diagram above shows.
Exercise
A robot on a grid can move forward one cell (cost 1) or turn 90 degrees in place (cost 1). Why is (row, col) not a good enough state, and what should the state be?
Show answer
The cost of reaching a neighboring cell depends on which way the robot is facing, because it may need to turn first. If you use only (row, col), situations with different future costs are merged into one node. Use (row, col, heading), where heading is one of four directions.
Exercise
In the diagram, breadth-first search from S could return S, A, G, since it has as few edges as S, B, G. What are the costs of the two paths, and which one is optimal?
Show answer
S, A, G costs 1 + 5 = 6, and S, B, G costs 2 + 2 = 4. S, B, G is optimal. Breadth-first search counts edges and ignores their weights.