Sub topic 10
Detecting Cycles in an Undirected Graph
This chapter assumes you know the DisjointSet class from the earlier chapters (parent array, union by size, path compression, and union returning True only when it merges two different sets). You should also be comfortable with graphs as lists of edges and with basic Big-O notation.
The idea
A cycle in an undirected graph is a path that starts and ends at the same vertex without reusing an edge. Union-find detects one with a single rule:
- Process the edges one at a time.
- If an edge joins two vertices that are already in the same set, those vertices are already connected by some other path. The new edge closes a loop, so the graph has a cycle.
- If the endpoints are in different sets, the edge merges two components and no cycle is created.
An undirected graph is acyclic (a forest) exactly when every edge merges two different sets.
The code
The function below reuses DisjointSet. It stops at the first edge that fails to merge.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.count = n # number of disjoint sets
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
# second pass: point every node on the path directly at the root
while self.parent[x] != root:
self.parent[x], x = root, self.parent[x]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same set
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.count -= 1
return True
def connected(self, a, b):
return self.find(a) == self.find(b)
def has_cycle(n, edges):
ds = DisjointSet(n)
for u, v in edges:
if not ds.union(u, v):
return True # u and v were already connected, so this edge closes a cycle
return False
print(has_cycle(4, [(0, 1), (1, 2), (2, 3)])) # False
print(has_cycle(4, [(0, 1), (1, 2), (2, 0), (2, 3)])) # TrueTracing the second example
For the edges (0, 1), (1, 2), (2, 0), (2, 3):
| Edge | Sets before | Result of `union` | Action |
|---|---|---|---|
| (0, 1) | {0} {1} {2} {3} | True | merge into {0,1} |
| (1, 2) | {0,1} {2} {3} | True | merge into {0,1,2} |
| (2, 0) | {0,1,2} {3} | False | return `True`, cycle found |
The edge (2, 3) is never examined. The function returns as soon as the cycle appears.
Cost
Each edge needs two find calls and at most one link. With union by size and path compression, each operation takes amortized time close to constant (inverse Ackermann). Checking E edges therefore costs about O(E), which is far less than the O(V + E) per search you would pay if you re-ran a depth-first search after every edge.
Common errors
- Self-loops. An edge
(v, v)has the same root on both sides, sounionreturnsFalseand the function reports a cycle. This is correct for a graph that allows self-loops, but check that your input is what you expect. - Parallel edges. Two copies of
(0, 1)also report a cycle. Whether that counts depends on whether your graph is a simple graph or a multigraph. Decide this before you use the result. - Directed graphs. This method does not work for directed graphs. In a directed graph, edges
0 -> 1,0 -> 2,1 -> 2form no directed cycle, yet the third edge joins two vertices that are already in the same set. Use depth-first search with colors or a topological sort there. - Ignoring the return value. If you call
ds.union(u, v)without checking what it returns, you lose the signal. Useds.countafterwards only if you need the number of components.
Why this leads to Kruskal's algorithm
Kruskal's algorithm needs the same test. It adds an edge to the spanning tree only when the edge does not close a cycle, which is the case where union returns True. The next chapter builds on this.
Exercise
A graph has 5 vertices (0 to 4) and the edges (0,1), (2,3), (3,4), (1,2), (4,0) in that order. Which edge does has_cycle report as closing the cycle, and what are the sets just before it?
Show answer
The edge (4, 0). After the first four edges, the sets are {0,1,2,3,4}, because (0,1), (2,3), (3,4) and (1,2) all merge different sets. Vertices 4 and 0 then share a root, so union(4, 0) returns False and has_cycle returns True.
Exercise
Why does this method give a wrong answer for the directed edges 0->1, 0->2, 1->2?
Show answer
Union-find ignores edge direction. The edge 1->2 joins vertices that are already in the same set, so it reports a cycle. In a directed graph these edges form no directed cycle, because you can never follow the arrows back to a start vertex.