Sub topic 4
Undirected Graphs: DFS with Parent Tracking
This chapter assumes you can read Python lists and loops, know what an adjacency list is, and understand depth-first search (DFS) at a conceptual level. The previous chapters define a cycle and review DFS. Here we put the two together for undirected graphs.
The core idea
DFS grows a tree from a start vertex. Each vertex is reached through exactly one tree edge. Tree edges alone can never form a cycle. So if DFS finds an edge that leads to a vertex it has already visited, and that edge is not the tree edge it just came in on, the graph has a second path between two vertices in the same tree. Two different paths between the same pair of vertices form a cycle.
The catch is that an undirected edge u–v is stored twice in the adjacency list: once under u and once under v. When DFS moves from u to v, it sees u again among v's neighbors. u is already visited, but this is the same edge seen from the other end, not a cycle. Parent tracking exists to skip that one edge.
The algorithm
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(4, [(0, 1), (1, 2), (2, 0), (2, 3)])) # TrueEach stack entry carries the vertex and the edge ID used to reach it. The start vertex uses -1 because no edge leads to it. Vertices are marked visited when they are pushed, so each vertex gets exactly one tree edge. Any later visit to a marked vertex through a different edge is a non-tree edge, which means a cycle.
Each vertex is pushed once and each edge is scanned twice, so the run time is O(V + E) and the extra memory is O(V + E).
Walking through the example
For edges (0,1), (1,2), (2,0), (2,3) with IDs 0 to 3:
| Step | Pop | Neighbors checked | Result |
|---|---|---|---|
| 1 | 0, parent −1 | 1 via e0, 2 via e2 | push 1 and 2 |
| 2 | 2, parent e2 | 1 via e1 | 1 already visited, e1 ≠ e2: cycle |
The traversal stops at step 2 and returns True. Vertex 3 is never reached, and it doesn't need to be.
Common errors
- Forgetting the outer loop. A disconnected graph can have its cycle in a component that the first DFS never reaches. Looping over every
startcovers all components. - Treating every visited neighbor as a cycle. Without the parent check, every graph with at least one edge reports a cycle.
- Reusing this on directed graphs. In a directed graph, reaching a visited vertex does not imply a cycle. A later chapter explains why and introduces three-color DFS.
Exercise
Without the line if eid == parent_edge: continue, what would has_cycle_undirected(2, [(0, 1)]) return, and why?
Show answer
It would return True. DFS pushes 1 from 0 via edge 0. When it pops 1, it sees 0 through that same edge, finds 0 visited, and wrongly reports a cycle, even though a single edge is not a cycle.
Exercise
Does the function report a cycle for edges [(0, 1), (0, 1)] on 2 vertices? Would a version that skips the parent vertex (instead of the parent edge) agree?
Show answer
Yes, it returns True. The second edge has ID 1, which differs from the parent edge ID 0, so reaching visited vertex 0 counts as a cycle. A parent-vertex version would skip both edges back to 0 and wrongly return False.