Sub topic 1
Graphs in brief: vertices, edges, direction, weights
Prerequisites
This chapter assumes you can write basic Python and know lists, tuples, dictionaries, and sets. You should also know loops and functions, and what a queue and a stack are. No graph theory is needed.
What a graph is
A graph is a set of vertices (also called nodes) and a set of edges that connect pairs of vertices. A vertex stands for a thing: a grid cell, a city, or a puzzle configuration. An edge stands for a relationship between two things, such as "you can move from here to there in one step".
Two vertices joined by an edge are neighbours. The number of edges at a vertex is its degree.
Most search problems reduce to questions about a graph: can I get from A to B, what is the fewest steps, what is the cheapest route. Once you pick the vertices and edges, the same few algorithms answer those questions.
Direction
An edge can be undirected or directed.
- An undirected edge works both ways. If you can step from cell A to cell B on an open grid, you can step back.
- A directed edge works one way only. A one-way street, a conveyor belt cell, or a puzzle move you cannot undo are directed.
In an undirected graph, an edge between A and B is the same as two directed edges, A to B and B to A. Many models silently assume moves are reversible. Check that assumption for each problem.
Weights
A weight (or cost) is a number attached to an edge. In an unweighted graph every edge counts the same, so the best path is the one with the fewest edges. In a weighted graph the best path is the one with the smallest total weight, which may use more edges.
| Property | Choices | Example |
|---|---|---|
| Direction | undirected or directed | open corridor or one-way door |
| Weight | none (all equal) or numeric | one step or 5 minutes through mud |
A first example
Here is a small directed, weighted graph written as a dictionary. Each key is a vertex. Each value maps a neighbour to the weight of the edge.
graph = {
"A": {"B": 1, "C": 4},
"B": {"C": 2, "D": 6},
"C": {"D": 3},
"D": {},
}
def path_cost(graph, path):
total = 0
for u, v in zip(path, path[1:]):
total += graph[u][v]
return total
print(path_cost(graph, ["A", "C", "D"]))
print(path_cost(graph, ["A", "B", "C", "D"]))The first path has fewer edges (2) and costs 7. The second has more edges (3) and costs 6. So "fewest steps" and "cheapest" can give different answers, which is why later chapters use different algorithms for each.
Edges here are directed: graph["A"] lists "B", but graph["B"] does not list "A", so you cannot go from B back to A.
Paths and cycles
A path is a sequence of vertices where each consecutive pair is joined by an edge. Its length is its number of edges, and its cost is the sum of the edge weights. A cycle is a path that returns to its starting vertex. Graphs with cycles are the usual case for grids and puzzles, because you can walk in a loop. A search must therefore remember which vertices it has already visited, or it can run forever.
Common errors
- Treating a one-way move as two-way, which lets the search find paths that do not exist.
- Using edge count when the problem asks for total cost.
- Forgetting that cycles exist, so the search revisits vertices without end.
Exercise
In the example graph, what is the cost of the path A, B, D, and how does it compare with A, C, D?
Show answer
A to B costs 1 and B to D costs 6, so A, B, D costs 7. A, C, D costs 4 + 3 = 7. Both paths have two edges and the same total cost of 7. The cheapest path is still A, B, C, D at cost 6.