Sub topic 2
Edge Cases, Union-Find, and Directed Cycle Detection
This chapter assumes you know Python, adjacency lists, depth-first search (DFS), and the parent-edge DFS from the previous chapter.
Edge Cases: Self-Loops, Parallel Edges, and Disconnected Graphs
Three inputs break naive undirected detectors:
- Self-loop
(u, u): this is a cycle of length 1. Skipping the parent vertex hides it. Skipping the parent edge ID catches it. - Parallel edges
(u, v)twice: these form a cycle of length 2. Tracking edge IDs treats the second copy as a separate edge, so the detector reports it. - Disconnected graphs: a single DFS from vertex 0 misses cycles in other components. Start a search from every unvisited vertex.
Undirected Graphs: Union-Find
Union-find keeps disjoint sets of connected vertices. If an edge joins two vertices that are already in the same set, that edge closes a cycle. This approach suits graphs whose edges arrive one at a time.
def has_cycle_union_find(n, edges):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for u, v in edges:
ru, rv = find(u), find(v)
if ru == rv:
return True
parent[ru] = rv
return False
print(has_cycle_union_find(3, [(0, 1), (1, 2)])) # False
print(has_cycle_union_find(2, [(0, 1), (0, 1)])) # True: parallel edges
print(has_cycle_union_find(1, [(0, 0)])) # True: self-loopUnion-find handles self-loops and parallel edges without any special code.
Classifying DFS Edges
In a directed DFS, every edge falls into one of four types:
| Edge type | Target vertex when the edge is explored |
|---|---|
| Tree | Unvisited, so DFS descends into it |
| Back | An ancestor still on the current path |
| Forward | A descendant that is already finished |
| Cross | Finished, in another subtree or an earlier DFS tree |
A directed graph has a cycle exactly when DFS finds a back edge. Parent tracking fails on directed graphs because an edge to a visited vertex may be a forward or cross edge, and neither of those means a cycle.
Directed Graphs: Three-Color DFS
The three colors are white (unvisited), gray (on the current path), and black (finished). An edge into a gray vertex is a back edge.
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle_directed(adj):
color = [WHITE] * len(adj)
def dfs(u):
color[u] = GRAY
for v in adj[u]:
if color[v] == GRAY:
return True
if color[v] == WHITE and dfs(v):
return True
color[u] = BLACK
return False
return any(color[u] == WHITE and dfs(u) for u in range(len(adj)))
print(has_cycle_directed([[1], [2], []])) # False
print(has_cycle_directed([[1], [2], [0]])) # TrueDirected Graphs: Kahn's Algorithm and Topological Order
Kahn's algorithm repeatedly removes vertices with in-degree zero. If it cannot remove every vertex, the graph has a cycle and no topological order exists.
from collections import deque
def has_cycle_kahn(adj):
n = len(adj)
indegree = [0] * n
for u in range(n):
for v in adj[u]:
indegree[v] += 1
queue = deque(u for u in range(n) if indegree[u] == 0)
removed = 0
while queue:
u = queue.popleft()
removed += 1
for v in adj[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
return removed < n
print(has_cycle_kahn([[1], [2], [0], [0]])) # TrueKahn's algorithm uses no recursion. It also produces a topological order as a by-product when the graph has no cycle.
Exercise
In the directed graph 0→1, 0→2, 1→2, DFS from 0 visits 1, then 2, and later checks the edge 0→2. Vertex 2 is already visited. Is there a cycle, and what type of edge is 0→2?
Show answer
There is no cycle. When 0→2 is checked, vertex 2 is black (finished), so 0→2 is a forward edge. Only an edge into a gray vertex, which is a back edge, signals a cycle.
Exercise
Why does union-find report a cycle for the single edge (3, 3)?
Show answer
find(3) == find(3), so both endpoints are already in the same set, and the edge closes a cycle of length 1.