Sub topic 1
Representing Graphs for Cycle Detection
Prerequisites
This chapter assumes you can read Python lists, functions, and loops. You should know what vertices, edges, directed graphs, and undirected graphs are. You should also understand depth-first search (DFS) at a conceptual level and Big-O notation.
Representing Graphs
Cycle detection code takes input in one of two forms:
| Form | Shape | Best for |
|---|---|---|
| Edge list | `[(u, v), ...]` | Union-find and incremental input |
| Adjacency list | `adj[u] = [neighbors]` | DFS and Kahn's algorithm |
For undirected graphs, store each edge in both endpoints' lists. Tag each entry with the edge's index. The index lets DFS tell apart the edge it just walked from a second, parallel edge between the same two vertices.
What Counts as a Cycle
In an undirected graph, a cycle is a walk that returns to its starting vertex without reusing an edge. A self-loop (u, u) is a cycle of length 1. Two parallel edges between u and v form a cycle of length 2.
In a directed graph, a cycle has to follow edge directions. The edges a→b and b→a form a cycle. The edges a→b, a→c, and b→c do not, even though they form a triangle when you ignore direction.
Depth-First Search Refresher
DFS goes as deep as it can along unvisited neighbors, then backtracks. Every vertex and every edge is handled a constant number of times, so DFS runs in O(V + E). The graph may be disconnected, so you have to start a new DFS from each vertex that is still unvisited.
Undirected Graphs: DFS with Parent Tracking
In an undirected graph, every edge appears from both of its endpoints. When DFS looks at the neighbors of v, it always sees the vertex it came from. That edge does not mean there is a cycle. If you skip the edge you arrived on, then reaching any vertex that is already visited proves a cycle.
def has_cycle_undirected(n, edges):
adj = [[] for _ in range(n)]
for i, (u, v) in enumerate(edges):
adj[u].append((v, i))
adj[v].append((u, i))
visited = [False] * n
for start in range(n):
if visited[start]:
continue
visited[start] = True
stack = [(start, -1)]
while stack:
u, parent_edge = stack.pop()
for v, eid in adj[u]:
if eid == parent_edge:
continue
if visited[v]:
return True
visited[v] = True
stack.append((v, eid))
return False
print(has_cycle_undirected(4, [(0, 1), (1, 2), (2, 3)])) # False
print(has_cycle_undirected(3, [(0, 1), (1, 2), (2, 0)])) # True
print(has_cycle_undirected(2, [(0, 1), (0, 1)])) # TrueExercise
Why does the function loop over every start vertex instead of running DFS once from vertex 0?
Show answer
The graph may be disconnected. A cycle in a component that does not contain vertex 0 would never be visited, so you need a separate DFS from each vertex that is still unvisited.