Pattern visualizer
Detect Cycle in Undirected Graph
In an undirected graph every edge is two-way, so a DFS walking from a vertex back to the one it just came from is not a cycle — it's just turning around. The trick is to track, for each vertex, WHICH neighbour is its parent in the DFS. Any other already-visited neighbour means a second path reaches that vertex, which is exactly what a cycle is. One component can finish clean while another closes a loop, so the search has to try every unvisited vertex as a fresh root, not stop after the first one. Animated on: 7 vertices, undirected edges 0-1, 1-2 (a tree) and 3-4, 4-5, 5-6, 6-3 (a ring) — does this graph contain a cycle?.
DFS with parent tracking: a visited neighbour that isn't your parent is a cycle
Badge = parent this vertex was reached from (- = component root)
DFS stack
0 starts a new component. Mark it visited with no parent — anything this DFS later finds already-visited outside of a parent link means two paths reach the same vertex, i.e. a cycle.
1FUNCTION hasCycle(n, adj):2 visited <- ARRAY OF n FALSE3 FOR v FROM 0 TO n - 14 IF NOT visited[v] AND DFS(v, -1)5 RETURN true6 RETURN false7FUNCTION DFS(u, parent):8 visited[u] <- true9 FOR EACH w IN adj[u]10 IF visited[w] AND w != parent11 RETURN true12 IF NOT visited[w] AND DFS(w, u)13 RETURN true14 RETURN false
← / → step · space play · Home restart