Cycles: when no order exists
🌍 In real life. Type =B1+1 into cell A1 of a spreadsheet and =A1*2 into B1, and the spreadsheet refuses: "circular reference". To work out A1 it needs B1, and to work out B1 it needs A1. Python says the same when module a imports b while b imports a, and a university would have a problem if Course X required Course Y while Y required X: nobody could ever start.
A cycle in a directed graph is a path of arrows that leads back to where it started. A cycle means no topological order exists, so a program that schedules work must detect one and say exactly where it is, so a person can break it.
The idea in one sentence: during DFS, keep each vertex marked on path while you are inside it; an arrow to a vertex still on the path closes a cycle, while an arrow to a vertex already done is harmless.
Its words:
- cycle: arrows a → … → a leading back to the start; a self-loop a → a is the shortest
- on path (often called grey): DFS has entered the vertex but not finished it; these vertices form the current path from the start
- done (often called black): DFS has finished the vertex and everything reachable from it, finding no cycle there
- back edge: an arrow to a vertex that is on the path; every cycle shows up as one
How it works, step by step:
- for each vertex not yet seen (in sorted order), start DFS
- on entering v: mark it on path and add it to the path list
- for each arrow v → w: if w is on path, the path from w to v plus the arrow back to w is a cycle; if w is unseen, visit it
- when every arrow is done: take v off the path and mark it done
- if DFS never finds such an arrow, there is no cycle
Watch A → B → C → A, with an extra arrow C → D. The path is orange; the arrow that closes the loop turns red:
Why "on path" and not just "seen". In the diamond A → B, A → C, B → D, C → D, DFS reaches D through B, finishes it, then meets D again from C. D has been seen, but there is no cycle: D is done, and nothing leads from D back up. A single "seen" set can't tell these apart and would cry cycle. An arrow to a vertex on the current path is different: that vertex can reach v (the path leads from it down to v), and now v reaches it, so the two paths make a loop. Conversely, any cycle is caught: the first of its vertices DFS enters stays on the path until everything reachable from it is done, and that includes the vertex just before it on the cycle, whose arrow back finds it on the path.
Kahn sees cycles too. Run Kahn's algorithm on a graph with a cycle and the vertices on the cycle never reach in-degree 0. Here D goes, and A, B and C get stuck:
What it costs, by counting. Like any DFS, each vertex is entered once and each arrow looked at once: O(V + E). Kahn finds out that a cycle exists for the same cost, but the left-over vertices include ones that merely sit after a cycle; DFS hands you the loop itself, which is what a person needs in order to fix it. For A → B → C → A plus C → D, DFS stops after entering just 3 vertices.
def has_cycle(graph):
state = {} # missing: not seen; "on path"; "done"
def visit(v):
state[v] = "on path"
for w in graph[v]:
if state.get(w) == "on path": # an arrow back into the path
return True
if w not in state and visit(w):
return True
state[v] = "done" # finished: no loop runs through v
return False
return any(v not in state and visit(v) for v in sorted(graph))
print(has_cycle({"A": ["B"], "B": ["C"], "C": ["A", "D"], "D": []}))
print(has_cycle({"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []})) # a diamond, no cycle
def find_cycle(graph):
state, path = {}, []
def visit(v):
state[v] = "on path"
path.append(v)
for w in graph[v]:
if state.get(w) == "on path":
return path[path.index(w):] + [w] # from w round to w again
if w not in state:
found = visit(w)
if found:
return found
path.pop()
state[v] = "done"
return []
for v in sorted(graph):
if v not in state:
found = visit(v)
if found:
return found
return []
print(find_cycle({"A": ["B"], "B": ["C"], "C": ["A", "D"], "D": []}))
print(find_cycle({"A": ["C"], "B": ["C", "D"], "C": ["E"], "D": ["E"], "E": ["F"], "F": []}))Mistakes and edge cases.
- one "visited" set for both states: reports a cycle in every diamond; keep "on path" and "done" apart
- forgetting to take v off the path: after v finishes it must become done, or later arrows into it look like back edges
- only starting from one vertex: a cycle not reachable from it is missed; start from every vertex not yet seen
- reporting the whole path: the path may begin before the loop does (D → A → B → C → A); the cycle starts at w, so slice from path.index(w)
- undirected graphs are different: there, every edge goes both ways, so the edge back to your parent is not a cycle; this lesson is about directed graphs
Quiz
DFS on A → B, A → C, B → D, C → D finishes D through B, then meets D again from C. What does that mean?
- Nothing: D is done, not on the path, so there is no cycle
- A cycle through D
- The graph is not a DAG
What does this print?
def find_cycle(graph): state, path = {}, [] def visit(v): state[v] = "on path" path.append(v) for w in graph[v]: if state.get(w) == "on path": return path[path.index(w):] + [w] # from w round to w again if w not in state: found = visit(w) if found: return found path.pop() state[v] = "done" return [] for v in sorted(graph): if v not in state: found = visit(v) if found: return found return [] print(find_cycle({"A": ["B"], "B": ["C"], "C": ["D"], "D": ["B"]}))What does this print?
def has_cycle(graph): state = {} # missing: not seen; "on path"; "done" def visit(v): state[v] = "on path" for w in graph[v]: if state.get(w) == "on path": # an arrow back into the path return True if w not in state and visit(w): return True state[v] = "done" # finished: no loop runs through v return False return any(v not in state and visit(v) for v in sorted(graph)) print(has_cycle({"A": ["A"]}), has_cycle({"A": ["B"], "B": []}))This says the diamond A → B, A → C, B → D, C → D has a cycle. Which line is wrong?
def has_cycle(graph): seen = set() def visit(v): seen.add(v) for w in graph[v]: if w in seen: return True if visit(w): return True return False return any(v not in seen and visit(v) for v in sorted(graph))Kahn's algorithm gets stuck with A, B, C and D left over. What do you know?
- There is a cycle, but not all four have to be on it
- All four are on one cycle
- The graph has no edges
Coding tasks
Write
has_cycle(graph): returnTrueif following arrows can ever lead back to where you started, otherwiseFalse.graphmaps every vertex to the vertices its arrows point to.Write
find_cycle(graph): run DFS from the vertices in sorted order, following arrows in the order listed. At the first arrow v → w where w is still on the path, return the cycle: the path from w to v, then w again. Return[]if there is no cycle.