Sub topic 6
Paths and cycles
This chapter assumes you can read an adjacency list stored as a dictionary of dictionaries and that you know what a vertex and an edge are. It also assumes you can follow a recursive function.
Paths
A path is a sequence of vertices in which each consecutive pair is joined by an edge. In a directed graph, each edge must be followed in its own direction. A path from A to C through B means edges A→B and B→C exist. B→A alone does not count.
Three terms are worth fixing now:
- Length is the number of edges in the path. A path of three vertices has length 2.
- Weight (in a weighted graph) is the sum of the edge weights along the path. Length and weight are different measures, and the path with the fewest edges is not always the cheapest.
- A simple path repeats no vertex. Unless a text says otherwise, "path" in this tutorial means a simple path.
def is_path(graph, vertices):
return all(v in graph[u] for u, v in zip(vertices, vertices[1:]))
def path_weight(graph, vertices):
return sum(graph[u][v] for u, v in zip(vertices, vertices[1:]))
graph = {"A": {"B": 4, "C": 1}, "B": {}, "C": {"B": 2}}
print(is_path(graph, ["A", "C", "B"])) # True
print(path_weight(graph, ["A", "C", "B"])) # 3
print(path_weight(graph, ["A", "B"])) # 4
print(is_path(graph, ["B", "A"])) # FalseThe path A, B has length 1 but weight 4. The path A, C, B has length 2 but weight 3. The last call returns False because the graph has no edge from B to A.
Cycles
A cycle is a path that starts and ends at the same vertex and repeats no other vertex. The edges A→B, B→C, C→A form a cycle of length 3. A graph with no cycles is acyclic.
The definition differs slightly by graph type:
| Graph type | What counts as a cycle |
|---|---|
| Directed | Follow edges in their direction and return to the start. A→B and B→A is a cycle of length 2. |
| Undirected | At least 3 vertices. Going along an edge and straight back along the same edge does not count. |
Here A, B, C, A is a cycle. D is reachable from the cycle, but no path leads back out of D, so D is not on any cycle.
Detecting a directed cycle
Run a depth-first search and track which vertices are on the current recursion path. If an edge points to a vertex that is still on that path, you have found a cycle. Finished vertices are safe to reach again, because they cannot lead back.
def has_cycle(graph):
state = {} # missing = unvisited, 1 = on current path, 2 = finished
def visit(u):
state[u] = 1
for v in graph[u]:
if state.get(v) == 1:
return True
if v not in state and visit(v):
return True
state[u] = 2
return False
return any(u not in state and visit(u) for u in graph)
acyclic = {"A": {"B": 1, "C": 1}, "B": {"D": 1}, "C": {"D": 1}, "D": {}}
cyclic = {"A": {"B": 1}, "B": {"C": 1}, "C": {"A": 1}}
print(has_cycle(acyclic)) # False
print(has_cycle(cyclic)) # TrueIn acyclic, D is reached twice, once from B and once from C. The second visit finds D already finished (state 2), so it is correctly not reported as a cycle.
Common errors
Two other mistakes come up often:
- Confusing a walk with a path. A walk may repeat vertices and edges. Counting walks instead of simple paths can give infinite or inflated answers when a cycle is present.
- Forgetting the recursion limit. The recursive search above can exceed Python's default recursion limit on a path of roughly a thousand vertices. For large graphs, use an explicit stack.
The cycle question matters again in later chapters. A directed graph with no cycles is a DAG, and reachability along paths defines connectivity.
Exercise
A directed graph has edges A→B, B→C, and A→C, with weights 5, 5, and 12. Which path from A to C has the fewest edges, which has the lowest weight, and does the graph contain a cycle?
Show answer
The path A, C has the fewest edges (length 1), with weight 12. The path A, B, C has length 2 but weight 10, which is lower. No edge returns to an earlier vertex, so the graph has no cycle.