Sub topic 5
Edge Cases: Self-Loops, Parallel Edges, and Disconnected Graphs
This chapter assumes you have read the previous chapter on DFS with parent tracking, that you can read Python, and that you know what an adjacency list is. Here we look at three kinds of input that break simple cycle detectors, and at one implementation that handles all of them.
Why "skip the parent vertex" is not enough
The usual undirected check says: when DFS at u sees a visited neighbor v, report a cycle unless v is u's parent. That rule assumes the graph is simple. A simple graph has no self-loops and at most one edge between any pair of vertices. Real inputs often break that assumption.
- A self-loop is an edge from a vertex to itself, such as
(4, 4). It is a cycle of length 1. - Parallel edges are two or more edges joining the same pair of vertices, such as two copies of
(2, 3). Together they form a cycle of length 2. - A disconnected graph has more than one component. A cycle can sit in a component that your starting vertex cannot reach.
How each case fails
| Input | Naive parent-vertex check | Cause |
|---|---|---|
| Parallel edges `(2,3)`, `(2,3)` | Misses the cycle | Both copies lead to the parent vertex, so both are skipped |
| Self-loop `(4,4)` | Usually finds it, but only by accident | `4` is visited and is not its own parent |
| Cycle in a component not reached from vertex 0 | Misses the cycle | DFS never visits that component |
The parallel-edge failure comes from tracking the wrong thing. What you need to skip is the one edge you arrived on, and every other edge back to the parent vertex must still count.
Track the parent edge, not the parent vertex
Give every edge an id (its index in the edge list) and store that id in the adjacency list. During DFS, skip only the edge whose id matches the one you used to reach the current vertex. An outer loop starts a fresh search from every vertex that has not been visited yet, so every component gets checked.
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(2, [(0, 1)])) # False
print(has_cycle_undirected(4, [(0, 1), (2, 3), (2, 3)])) # True: parallel edges
print(has_cycle_undirected(5, [(0, 1), (4, 4)])) # True: self-loop
print(has_cycle_undirected(4, [(0, 1), (2, 3)])) # False: forestHere is how each case is now handled:
- Parallel edges: the two copies of
(2, 3)have ids 1 and 2. Vertex 3 is reached through id 1, so it skips id 1 but sees vertex 2 again through id 2, which is reported as a cycle. - Self-loops: the loop
(4, 4)is added toadj[4]twice with the same id. That id is never the parent edge, and4is already visited, so the cycle is reported on purpose this time. - Disconnected graphs: the
for start in range(n)loop starts a new search in each component, so no component is skipped.
The cost is still O(V + E). Each vertex goes onto the stack once, and each edge is scanned twice, once from each endpoint.
Exercise
A detector skips any neighbor equal to the parent vertex and starts DFS only from vertex 0. For the edges [(0, 1), (2, 3), (3, 2)] on 4 vertices, what does it return, and which two defects cause that result?
Show answer
It returns False, which is wrong. Starting only from vertex 0 means it never visits vertices 2 and 3. Even if it did reach them, skipping by parent vertex would skip both edges between 2 and 3, so the length-2 cycle formed by the parallel edges would still be missed.
Exercise
Why does the parent-edge version not report a false cycle on the single edge (0, 1)?
Show answer
Vertex 1 is reached through edge id 0. When it scans its neighbors, the only entry is (0, 0), and that id equals its parent edge, so it is skipped. No other edge leads to a visited vertex.