Sub topic 7
Detecting Cycles While Sorting
This chapter assumes you already know how Kahn's algorithm and the DFS-based sort work from the previous chapters. It also assumes you are comfortable with Python dictionaries and recursion. Here the focus moves from producing an order to explaining why no order exists.
A topological order exists only for a DAG. Real dependency data often contains mistakes, such as two packages that require each other. A good sorter does more than fail in that case. It tells the user which nodes caused the problem.
What Kahn's Algorithm Leaves Behind
Kahn's algorithm only removes nodes whose in-degree reaches zero. A node on a cycle always keeps at least one incoming edge from another node on the same cycle, so it is never removed. When the queue runs dry, any node with a positive in-degree is stuck.
from collections import deque
def kahn_with_report(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
queue = deque(u for u, d in indegree.items() if d == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in graph.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
stuck = [u for u, d in indegree.items() if d > 0]
return order, stuck
pipeline = {
"setup": ["build"],
"build": ["test"],
"test": ["build", "deploy"],
"deploy": [],
}
print(kahn_with_report(pipeline))
# (['setup'], ['build', 'test', 'deploy'])Recovering the Exact Cycle with DFS
In the DFS version, a GRAY node is one whose visit has started but not finished. That means it is on the current recursion path. An edge to a GRAY node is a back edge, and it closes a cycle. If you record each node's parent as you descend, you can follow parents from the current node back to the GRAY node to rebuild the loop.
def find_cycle(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color = {}
parent = {}
def visit(u):
color[u] = GRAY
for v in graph.get(u, []):
c = color.get(v, WHITE)
if c == GRAY:
cycle = [v]
x = u
while x != v:
cycle.append(x)
x = parent[x]
cycle.append(v)
cycle.reverse()
return cycle
if c == WHITE:
parent[v] = u
found = visit(v)
if found:
return found
color[u] = BLACK
return None
for u in graph:
if color.get(u, WHITE) == WHITE:
found = visit(u)
if found:
return found
return None
print(" -> ".join(find_cycle({"a": ["b"], "b": ["c"], "c": ["a"], "d": ["a"]})))
# a -> b -> c -> aAn edge to a BLACK node does not indicate a cycle. A BLACK node has finished, so every node reachable from it has already been fully explored. Treating BLACK like GRAY is the most common bug in hand-written DFS cycle detectors. It reports false cycles in diamond-shaped graphs such as a → b → d and a → c → d.
Choosing a Method
| Concern | Kahn's algorithm | DFS with colors |
|---|---|---|
| Detects that a cycle exists | Yes, `len(order) < V` | Yes, edge to a GRAY node |
| Reports the exact cycle | No, only the stuck nodes | Yes, through parent pointers |
| Stops early | No, finishes the queue first | Yes, at the first back edge |
| Deep graphs | Iterative, so it is safe | Recursion can hit Python's limit |
Edge Cases to Test
- Self-loop (
u → u): Kahn never lowersu's in-degree to zero. DFS seesuas GRAY from inside its own visit. Both methods handle it, andfind_cyclereturns[u, u]. - Cycle in a disconnected part: the outer loop over all nodes makes sure DFS still reaches the cycle.
- Nodes listed only as targets: use
.getwith a default, as both examples do, so a node with no entry of its own does not raise aKeyError.
Exercise
Run kahnwithreport on {"x": ["y"], "y": ["z"], "z": ["y"], "w": []}. Which nodes are in the returned order, which are stuck, and which stuck nodes actually lie on the cycle?
Show answer
The order is ['x', 'w'] and the stuck list is ['y', 'z']. Both y and z lie on the cycle y -> z -> y. Removing x lowers y's in-degree from 2 to 1, but it never reaches 0.
Exercise
Why does find_cycle report no cycle for {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}, even though d is reached twice?
Show answer
The second time DFS reaches d, d is already BLACK because its visit has finished. Only an edge to a GRAY node, which is still on the recursion path, closes a cycle.