Sub topic 4
Undirected Graphs: DFS with Parent Tracking
This chapter assumes you can read Python functions and loops, build an adjacency list from an edge list, and follow depth-first search (DFS) at the level of the previous chapter. It also uses the earlier definition of a cycle: in an undirected graph, a cycle is a closed walk that never reuses an edge. A self-loop counts as a cycle, and so does a pair of parallel edges.
The Core Idea
DFS on an undirected graph builds a spanning forest. Each vertex is discovered through exactly one edge, called its tree edge or parent edge. Any other edge between two discovered vertices closes a loop. The DFS tree already holds a path between those two vertices, and the extra edge connects the ends of that path.
So the detection rule is short. While exploring vertex u, look at each incident edge. If the edge leads to an already visited vertex and it is not the edge you used to reach u, you have found a cycle.
The exception matters because every edge in an undirected graph appears in both adjacency lists. When DFS moves from p to u along edge (p, u), the list for u contains p again. p is visited, so without the exception every tree edge would look like a cycle.
Why the Rule Is Correct
Two claims carry the proof.
- A reported edge really closes a cycle. Suppose
usees a visited vertexvthrough edgee, andeis notu's parent edge. Both vertices lie in the same DFS tree, so the tree contains a path fromvtou. That path uses only tree edges. Edgeeis not the tree edge intou. It cannot be the tree edge intoveither, becausevwas reached from some other vertex, orvis the root. The tree path followed byeis therefore a closed walk with no repeated edge. - Every cycle gets reported. A forest on
Vvertices withccomponents has exactlyV − cedges. If the graph has a cycle, at least one edge is left out of the DFS forest. When the algorithm scans that edge from either endpoint, both endpoints are already visited or about to be, and the edge is not a parent edge. The scan reports it.
The proof never uses the depth-first order. It needs only "spanning forest plus one extra edge." That is why the stack-based version later in the chapter can mark vertices when they are pushed, and why BFS with the same parent rule also works.
A Recursive Implementation
The recursive version is the clearest way to see the model. It skips the parent by edge ID rather than by parent vertex. The next chapter explains in detail why this choice matters for parallel edges.
def has_cycle_recursive(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
def dfs(u, parent_edge):
visited[u] = True
for v, eid in adj[u]:
if eid == parent_edge:
continue
if visited[v]:
return True
if dfs(v, eid):
return True
return False
for s in range(n):
if not visited[s] and dfs(s, -1):
return True
return False
edges = [(0, 1), (1, 2), (2, 3), (3, 1), (0, 4)]
print(has_cycle_recursive(5, edges)) # True
print(has_cycle_recursive(5, [(0, 1), (1, 2), (0, 4)])) # FalseThe outer loop over s is part of the algorithm. A graph can have several connected components, and a cycle in any of them makes the whole graph cyclic. The root of each component gets parent_edge = -1, which matches no real edge.
Tracing the Example
The example graph has edges e0=(0,1), e1=(1,2), e2=(2,3), e3=(3,1), and e4=(0,4). Vertices 1, 2, and 3 form a triangle.
| Step | Call | Edge examined | Result |
|---|---|---|---|
| 1 | `dfs(0, -1)` | `e0` to 1 | 1 unvisited, recurse |
| 2 | `dfs(1, e0)` | `e0` to 0 | parent edge, skip |
| 3 | `dfs(1, e0)` | `e1` to 2 | 2 unvisited, recurse |
| 4 | `dfs(2, e1)` | `e1` to 1 | parent edge, skip |
| 5 | `dfs(2, e1)` | `e2` to 3 | 3 unvisited, recurse |
| 6 | `dfs(3, e2)` | `e2` to 2 | parent edge, skip |
| 7 | `dfs(3, e2)` | `e3` to 1 | 1 visited, not parent edge: **cycle** |
Vertex 4 is never visited because the search stops early. The tree path 1 → 2 → 3 plus edge e3 is the cycle. A later chapter shows how to recover that path from stored parent pointers.
An Iterative Implementation
Python's default recursion limit is about 1000 frames, so has_cycle_recursive raises RecursionError on a path graph with a few thousand vertices. The version below uses an explicit stack. It marks a vertex as visited when the vertex is pushed, not when it is popped.
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(5, [(0, 1), (1, 2), (2, 3), (3, 1), (0, 4)])) # True
print(has_cycle_undirected(4, [(0, 1), (2, 3)])) # False
print(has_cycle_undirected(2, [(0, 1), (0, 1)])) # True
print(has_cycle_undirected(1, [(0, 0)])) # True
print(has_cycle_undirected(100_000, [(i, i + 1) for i in range(99_999)])) # FalseThis visit order is not true DFS order. Push-time marking produces a mix of depth-first and breadth-first behavior. That is fine, because the correctness argument relies only on the spanning forest. The edge that marks v becomes v's parent edge, and each vertex is marked exactly once. Any other edge that reaches a marked vertex is therefore a non-forest edge.
Marking at push time also prevents duplicate stack entries. Each vertex is pushed and popped at most once, so the stack never holds more than V entries.
The last two calls in the snippet test the multigraph cases. With two parallel edges (0,1), vertex 1 is reached via edge 0 and then sees vertex 0 again via edge 1, so the function reports a cycle. The self-loop (0,0) adds (0, 0) to adj[0] twice with the same ID. On the first scan, vertex 0 is visited and edge 0 is not the root's parent edge, so the function reports a cycle.
Complexity
| Resource | Cost | Reason |
|---|---|---|
| Time | O(V + E) | Each vertex is processed once; each adjacency entry (2E total) is scanned at most once |
| Extra space | O(V + E) | Adjacency list O(V + E), plus `visited` and the stack, both O(V) |
| Early exit | Yes | Returns at the first non-tree edge, often well before scanning every edge |
The worst case for time is an acyclic graph. Without a cycle there is nothing to stop the search early, so every edge gets scanned.
Common Errors
- Only searching from vertex 0. A cycle in another component goes unnoticed. Always loop over every start vertex.
- Mixing marking styles in the iterative version. If you check
visitedwhen scanning a neighbor but set it only when popping, a vertex can be pushed twice from two different neighbors. The second push carries a different parent edge, so the code can report false cycles or stop matching the proof. Choose push-time marking with the push-time check, as shown above. - Treating
parent_edge = -1carelessly. If you useNone, or use0for the root, edge 0 gets silently skipped when it starts at the root. - Running this on a directed graph. In a directed graph, an edge into a visited vertex can be a cross edge or forward edge that closes no cycle. The DAG 0→1, 0→2, 2→1 would be wrongly reported as cyclic. Directed graphs need the three-color method from a later chapter.
Exercise
For edges [(0, 1), (1, 2), (2, 0)], trace hascyclerecursive(3, edges). Which call detects the cycle, and through which edge ID?
Show answer
dfs(0, -1) takes e0 to 1. dfs(1, e0) skips e0 and takes e1 to 2. dfs(2, e1) skips e1 and then sees e2 leading to vertex 0, which is visited and is not the parent edge. dfs(2, e1) reports the cycle through edge e2.
Exercise
A student writes the parent check as if v == parent: continue, tracking the parent vertex. Give the smallest input on which this version returns the wrong answer, and explain why.
Show answer
n = 2, edges [(0, 1), (0, 1)]. The correct answer is True, because two parallel edges form a cycle of length 2. Vertex 1's adjacency list holds vertex 0 twice, and both entries match the parent vertex, so both are skipped. Vertex 0's scan reaches 1 through the first edge and then finds 1 already visited... only if the scan order lets it. With push-time marking in the iterative version, vertex 0 marks 1 on the first edge and sees it visited on the second, so that order would catch the cycle. In the recursive version, dfs(0) recurses into 1 first. Vertex 1 skips both copies of 0, and when control returns to vertex 0, its second edge sees 1 visited with v != parent (0 is the root, so parent is -1). The recursive version therefore also catches it. The input that fails reliably is a graph whose only cycle is a parallel pair seen from the child's side, such as edges [(1, 0), (0, 1)] scanned from root 0 with adj[0] = [1, 1]. Edge IDs avoid this question entirely, because each copy has its own ID and only the one actually used is skipped.
Exercise
Without running DFS, decide whether a graph with 6 vertices and 6 edges can be acyclic. What about 6 vertices and 4 edges?
Show answer
With 6 edges it cannot be acyclic, because a forest on 6 vertices has at most 5 edges, so E ≥ V guarantees a cycle. With 4 edges the count proves nothing. The graph could be a forest with 2 components, or it could contain a triangle plus isolated vertices, so you must run the search.
Exercise
Why can the iterative version mark vertices at push time even though that changes the visiting order away from true DFS?
Show answer
The correctness proof needs only two facts: every vertex is marked exactly once through a single edge, and those edges form a spanning forest. Any other edge between marked vertices is outside that forest and closes a cycle. Visiting order does not appear in the argument, so push-time marking, true DFS, and BFS all give correct answers.