Sub topic 6
Paths and cycles
This chapter assumes you can read the dictionary-of-dictionaries adjacency list used earlier in this tutorial. It also assumes you know what degree means, and that you can write a depth-first search with a stack or recursion. Paths and cycles describe how you move through a graph. Connectivity, traversal, shortest paths and DAGs all build on them.
Walks, trails, paths, and cycles
Moving through a graph means following edges from vertex to vertex. Texts use several related words for this, and they differ in what they allow you to repeat.
| Term | Definition | Repeated vertices | Repeated edges |
|---|---|---|---|
| Walk | A sequence of vertices where each consecutive pair is joined by an edge | Allowed | Allowed |
| Trail | A walk that uses no edge twice | Allowed | Not allowed |
| Path | A walk that visits no vertex twice | Not allowed | Not allowed |
| Cycle | A walk that starts and ends at the same vertex and repeats nothing else | Only start = end | Not allowed |
Authors are not consistent. Some books use "path" for what is called a walk here, and call the no-repeat version a "simple path". This chapter uses "path" to mean no repeated vertices. Check the definition whenever you read another source.
Every path is a trail, and every trail is a walk. The reverse is false. In an undirected graph with edges A-B and B-C, the sequence A, B, A, B, C is a walk. It reuses the edge A-B, so it is not a trail, and it revisits A and B, so it is not a path.
Length: edges or weight
The length of a path is the number of edges it uses. A path through k vertices has length k - 1. In a weighted graph you usually also want the weight of the path, which is the sum of its edge weights. These are different quantities, and mixing them up is a common source of bugs. The path with the fewest edges is not always the cheapest one.
Direction matters
In a directed graph, a path must follow edges in their stated direction. If the only edge is A → B, then A, B is a path and B, A is not. In an undirected graph each edge works both ways, so any path can be reversed.
Checking a path in code
The adjacency list lets us test each step with a dictionary lookup. This version works for undirected, directed and weighted graphs alike.
def is_path(graph, vertices):
if not vertices:
return False
if any(v not in graph for v in vertices):
return False
if len(set(vertices)) != len(vertices):
return False
return all(b in graph[a] for a, b in zip(vertices, vertices[1:]))
def path_weight(graph, vertices):
return sum(graph[a][b] for a, b in zip(vertices, vertices[1:]))
g = {
"A": {"B": 4, "C": 1},
"B": {"A": 4, "C": 2},
"C": {"A": 1, "B": 2},
}
print(is_path(g, ["A", "C", "B"])) # True
print(path_weight(g, ["A", "C", "B"])) # 3
print(path_weight(g, ["A", "B"])) # 4
print(is_path(g, ["A", "C", "A"])) # False: A repeatsThe path A, C, B has two edges but weight 3. The single edge A, B has length 1 but weight 4. By edge count the direct route is shorter, and by weight the two-edge route is cheaper.
A single vertex counts as a path of length 0. The code above agrees: a one-element list passes every check, and the final all(...) over an empty set of pairs is true.
What counts as a cycle
A cycle is a path that returns to its starting point. Formally, it is a walk v0, v1, ..., vk with v0 = vk, no repeated edges, and no repeated vertices other than the start and end.
The minimum size of a cycle depends on the graph type.
- In a simple undirected graph, a cycle needs at least 3 vertices. The walk A, B, A reuses the edge A-B, so it is not a cycle.
- In a directed graph, A → B → A is a valid cycle of length 2, because the two edges are different edges.
- A self-loop, an edge from a vertex to itself, is a cycle of length 1 in both kinds of graph.
A graph with no cycles is acyclic. An undirected acyclic graph is a forest, and a connected one is a tree. A directed graph with no cycles is a DAG, which a later chapter covers.
Detecting cycles in an undirected graph
Run a depth-first search and watch for an edge that leads to a vertex you have already seen. There is one exception. Every undirected edge can be walked back, so the edge to the vertex you just came from does not count. Track each vertex's parent, the vertex that discovered it, and skip it.
def has_cycle_undirected(graph):
seen = set()
for root in graph:
if root in seen:
continue
seen.add(root)
stack = [(root, None)]
while stack:
u, parent = stack.pop()
for v in graph[u]:
if v == u:
return True
if v == parent:
continue
if v in seen:
return True
seen.add(v)
stack.append((v, u))
return False
line = {"A": {"B": 1}, "B": {"A": 1, "C": 1}, "C": {"B": 1}}
triangle = {
"A": {"B": 1, "C": 1},
"B": {"A": 1, "C": 1},
"C": {"A": 1, "B": 1},
}
print(has_cycle_undirected(line)) # False
print(has_cycle_undirected(triangle)) # TrueThe outer loop over root matters. The graph may have several components, and a cycle might sit in one the first search never reaches. Each vertex and edge is examined a constant number of times, so the running time is O(V + E).
This code assumes a simple graph, meaning at most one edge between a pair of vertices. A dictionary cannot hold two parallel edges between the same pair. If you need multigraphs, store edges as a list of records and compare edge identities instead of parent vertices.
Detecting cycles in a directed graph
The parent trick fails for directed graphs, and a plain "already seen" test is wrong too. Take the edges A → B, A → C and B → C. Vertex C is reached twice, but there is no directed cycle. The two visits arrive along different routes, and neither route leads back to A.
The correct test is whether the edge leads to a vertex that is still on the current search path. Colors track this.
- White: not discovered yet.
- Gray: discovered, and its search is still in progress, so it is on the current path.
- Black: finished completely.
An edge into a gray vertex closes a cycle. An edge into a black vertex is harmless, because everything reachable from it has already been explored without returning here.
def find_cycle(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color = {u: WHITE for u in graph}
parent = {}
def visit(u):
color[u] = GRAY
for v in graph[u]:
if color[v] == GRAY:
cycle = [u]
while cycle[-1] != v:
cycle.append(parent[cycle[-1]])
cycle.reverse()
cycle.append(v)
return cycle
if color[v] == WHITE:
parent[v] = u
found = visit(v)
if found:
return found
color[u] = BLACK
return None
for u in graph:
if color[u] == WHITE:
found = visit(u)
if found:
return found
return None
looped = {"A": {"B": 1}, "B": {"C": 1}, "C": {"A": 1, "D": 1}, "D": {}}
dag = {"A": {"B": 1, "C": 1}, "B": {"C": 1}, "C": {}}
print(find_cycle(looped)) # ['A', 'B', 'C', 'A']
print(find_cycle(dag)) # NoneWhen the search finds a gray vertex v from u, the parent links lead from u back up to v. Reversing that chain and appending v gives the cycle itself. Returning the cycle is more useful than returning a boolean, because you can show a user which items depend on each other.
The same three-color idea underlies dependency checkers and build systems. This version recurses, so a very deep graph can exceed Python's recursion limit of about 1000 frames. For large graphs, convert it to an explicit stack or raise the limit with sys.setrecursionlimit.
Common errors
- Counting a back-and-forth step as an undirected cycle. A, B, A reuses an edge. Skip the parent, or compare edge identities in multigraphs.
- Treating "visited before" as "on a cycle" in directed graphs. Distinguish gray from black.
- Reporting the cycle's vertices without the repeated endpoint, or with it, inconsistently. Pick one convention. This chapter lists the start vertex again at the end.
- Confusing length with weight. Use "length" for edges and "weight" for the sum of edge values.
- Forgetting to start a search from every unvisited vertex, which misses cycles in other components.
Exercise
In the directed graph with edges A → B, B → C, C → B and C → D, find a cycle and give its length. Does the undirected version of this graph have a cycle that uses A?
Show answer
The cycle is B → C → B, with length 2. In the undirected version, A is attached by a single edge to B, so A is a leaf and no cycle can pass through it. A cycle needs every vertex on it to have two distinct cycle edges, and A has only one edge. In the undirected version, B-C is a single edge (the two directed edges collapse into one), so there is no cycle at all.
Exercise
A weighted undirected graph has edges A-B (weight 1), B-C (weight 1), C-D (weight 1) and A-D (weight 10). List the two paths from A to D. Which has fewer edges, and which has the smaller weight?
Show answer
The paths are A, D and A, B, C, D. A, D has 1 edge and weight 10. A, B, C, D has 3 edges and weight 3. The direct path has fewer edges, but the three-edge path has the smaller weight.