Sub topic 5
Edge Cases: Self-Loops, Parallel Edges, and Disconnected Graphs
This chapter assumes you have read the earlier chapters on graph representation, the definition of a cycle, and undirected DFS with parent tracking. You should be comfortable reading Python that builds adjacency lists from edge lists.
Most cycle-detection bugs come from inputs the author never tested: a vertex with an edge to itself, two edges between the same pair of vertices, or a graph that falls apart into several pieces. The algorithm is often fine. The bug sits in how the graph was built or in a loop that stops too early. This chapter goes through each case, shows what the correct answer is, and shows where common code gets it wrong.
The Three Edge Cases and Their Correct Answers
Before testing code, fix the expected answers. A self-loop is an edge whose two endpoints are the same vertex. Parallel edges (also called multi-edges) are two or more distinct edges joining the same pair of vertices. A graph that allows them is a multigraph. A disconnected graph has two or more components, and no path joins vertices in different components.
| Input | Undirected answer | Directed answer |
|---|---|---|
| Self-loop `u–u` / `u→u` | Cycle of length 1 | Cycle of length 1 |
| Two parallel edges between `u` and `v` | Cycle of length 2 | Not a cycle if both are `u→v` |
| `u→v` plus `v→u` | Same as parallel edges | Cycle of length 2 |
| Cycle only in a second component | Cycle | Cycle |
| No vertices, or only isolated vertices | No cycle | No cycle |
The middle rows are where undirected and directed graphs differ. In an undirected multigraph, two separate edges between u and v let you leave u on one edge and come back on the other without reusing an edge, so they form a cycle. In a directed graph, two copies of u→v give you no way back to u. You need an edge pointing the other way.
Why Edge IDs Make the Undirected Rule Exact
The undirected DFS from the earlier chapter skips the edge it arrived on, identified by its index, rather than the vertex it came from. Here is that function again, since every test below uses it:
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 FalseThe rule reads: "any edge other than the one I came in on that reaches a visited vertex closes a cycle." Each edge case follows from it directly.
- Self-loop at
u. The edge appears inadj[u]twice, both times pointing touwith the same ID. That ID is never the edge used to reachu, anduis already visited, so the function returnsTrue. - Parallel edges
u–vwith IDs 3 and 7. Ifvwas reached through edge 3, the entry for edge 7 is a different ID that leads to a visited vertex, so it counts as a cycle. - Disconnected graph. The outer
for start in range(n)loop starts a new search in every component that has not been visited yet.
A version that skips the parent vertex also reports parallel edges in this traversal, but only by luck of ordering. From the child's side, both copies point to the parent vertex and get skipped. Only the parent's side catches the second copy. The edge-ID rule makes the right decision at either endpoint, so you can check correctness one edge at a time. It also gives the correct 2-vertex cycle when you reconstruct cycles later.
Tests That Pin Down the Answers
Turn the table into tests and run them every time you change the code:
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
tests = [
("empty graph", 0, [], False),
("isolated vertices", 3, [], False),
("self-loop", 1, [(0, 0)], True),
("parallel edges", 2, [(0, 1), (0, 1)], True),
("tree", 4, [(0, 1), (1, 2), (1, 3)], False),
("cycle in second component", 6,
[(0, 1), (1, 2), (3, 4), (4, 5), (5, 3)], True),
]
for name, n, edges, expected in tests:
got = has_cycle_undirected(n, edges)
status = "ok" if got == expected else "FAIL"
print(f"{status:4} {name}: expected {expected}, got {got}")All six lines print ok. The "cycle in second component" case is the one that catches a missing outer loop. If you replace the loop with a single search from vertex 0, the search sees only the tree 0–1–2 and returns False.
Where Real Code Goes Wrong: Building the Graph
The detection loop above is correct. Most failures happen earlier, when the input is turned into an adjacency structure.
Sets silently remove parallel edges
Storing neighbors in a set is a common habit, because it makes membership tests fast. It also merges parallel edges into one:
def build_adj_set(n, edges):
adj = [set() for _ in range(n)]
for u, v in edges:
adj[u].add(v)
adj[v].add(u)
return adj
adj = build_adj_set(2, [(0, 1), (0, 1)])
print(adj) # [{1}, {0}]
print(len(adj[0])) # 1: the second edge is goneAny algorithm that runs on this structure sees a single edge and reports no cycle. Graph libraries do the same thing: a networkx.Graph keeps one edge per vertex pair, and you need networkx.MultiGraph to keep parallel edges.
Filtering out self-loops
Input-cleaning code sometimes contains if u == v: continue to "ignore bad edges." For cycle detection, that line deletes a cycle. If self-loops really are invalid in your domain, reject the input with an error so the problem is visible. Dropping them silently hides it.
Mirrored edge lists cause false positives
Some data formats list every undirected edge twice, once in each direction, such as (0, 1) and (1, 0). The edge-ID code treats these as two parallel edges and reports a cycle that does not exist:
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
def dedupe_mirrored(edges):
seen = set()
result = []
for u, v in edges:
key = (min(u, v), max(u, v))
if key not in seen:
seen.add(key)
result.append((u, v))
return result
mirrored = [(0, 1), (1, 0), (1, 2), (2, 1)]
print(has_cycle_undirected(3, mirrored)) # True (wrong)
print(has_cycle_undirected(3, dedupe_mirrored(mirrored))) # False (right)Labels that are not 0 to n-1
The functions in this tutorial index arrays by vertex number. If your vertices are strings, or integers with gaps, map them to indices first, for example with index = {label: i for i, label in enumerate(labels)}. An isolated vertex that appears in no edge still needs an index if you want to report it. It cannot create a cycle, but leaving it out makes n wrong.
The Same Cases in Directed Graphs
Three-color DFS handles these cases with no special code:
- A self-loop
u→uis examined whileuis gray, so it is reported as a back edge. - Parallel
u→vedges are examined twice. The second time,vis black or still on the path. It is reported only ifvreally is an ancestor ofu. any(... for u in range(len(adj)))starts a search from every unvisited vertex, which covers every component.
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle_directed(adj):
color = [WHITE] * len(adj)
def dfs(u):
color[u] = GRAY
for v in adj[u]:
if color[v] == GRAY:
return True
if color[v] == WHITE and dfs(v):
return True
color[u] = BLACK
return False
return any(color[u] == WHITE and dfs(u) for u in range(len(adj)))
print(has_cycle_directed([[0]])) # True: self-loop
print(has_cycle_directed([[1, 1], []])) # False: parallel u->v edges
print(has_cycle_directed([[1], [0]])) # True: u->v and v->u
print(has_cycle_directed([[], [2], [1]])) # True: cycle away from vertex 0Kahn's algorithm, covered in a later chapter, handles them too. A self-loop adds 1 to the vertex's own in-degree, which never drops to zero. Parallel edges add to the in-degree twice and are removed twice, so they cancel out.
Exercises
Exercise
A colleague builds an undirected graph with adj[u].add(v); adj[v].add(u) using sets, then runs a correct DFS cycle detector. For the edge list [(0, 1), (1, 2), (2, 1)], which is a multigraph, what does the detector report, and what is the correct answer?
Show answer
The sets merge (1, 2) and (2, 1) into one edge, so the detector sees the path 0–1–2 and reports no cycle. The correct answer for a multigraph is a cycle of length 2 between vertices 1 and 2. Use lists of (neighbor, edge_id) pairs so that parallel edges stay separate.
Exercise
Why does has_cycle_undirected(3, [(0, 1), (1, 0)]) return True, and is this a bug in the function or in how it was called?
Show answer
The function gives the two tuples different edge IDs, 0 and 1, and so treats them as parallel edges, which do form a cycle in a multigraph. The function is right for the input it was given. The bug is in the call: if the format lists each undirected edge in both directions, the caller must deduplicate first. If the input really is a multigraph, the answer True is correct.
Exercise
In a directed graph with adjacency list [[1], [2], [2], [0]], is there a cycle? Which vertex does the outer loop of three-color DFS need to reach before the cycle is found?
Show answer
Yes. Vertex 2 has a self-loop 2→2. The search from vertex 0 visits 0, then 1, then 2, and finds the self-loop while 2 is gray, so vertex 0 alone is enough. Vertex 3 has an edge to 0 but is not reachable from 0. The outer loop would start a separate search from 3 if no cycle had been found yet.