Cycle Detection
Does a path exist that starts and ends at the same vertex without retracing an
edge? The answer splits on direction: an undirected graph only needs a
visited set plus the parent you arrived from, while a directed graph
needs to distinguish "still on my current path" from "already finished," which
takes a third state.
The full derivation - the WHITE/GRAY/BLACK colouring, why a back edge is a cycle, why parent-skip is required in undirected and a bug in directed, and the BFS forms of both - lives on Cycles & Ordering.
Undirected
Undirected Graph Cycle
Medium·
2 Approachesclick to switch
1
DFS
O(V + E)
O(V + E)
2
BFS
O(V + E)
O(V + E)
FIG. UNDIRECTED GRAPH CYCLE● INTERACTIVE
visualization loads as you reach it
- Time
- O(V + E)
- Building
graphscans every edge twice (once per direction):O(E). dfs_cycle_detectionadds each node tovisitedonce and, thanks to theif node not in visitedguard in the outer loop, is only ever called from a fresh start once per node; each edge is examined from both endpoints across the whole run:O(V + E).Vis the number of vertices andEis the number of edges.- Space
- O(V + E)
graphstores both directions of every edge,O(E).visitedholds up toVentries, and the recursion stack goes at mostVdeep:O(V).
Directed
Directed Graph Cycle
Medium·
2 Approachesclick to switch
1
DFS
O(V + 2E)
O(3V + E)
2
BFS - Khan's algorithm
O(2V + 2E)
O(3V + E)
FIG. DIRECTED GRAPH CYCLE● INTERACTIVE
visualization loads as you reach it
- Time
- O(V + 2E)
- Building
graphfromedgesis one O(E) pass over the edge list. - The DFS then visits each of the
Vnodes exactly once (thevisitedguard stops re-entry) and, across all recursive calls, follows each of theEedges once - an O(V + E) traversal. - The two O(E) contributions (the build pass and the traversal's edge-following) combine into a coefficient: O(V + 2E).
- Space
- O(3V + E)
graphstoresVkeys andEtotal neighbor entries across its adjacency lists - O(V + E).visitedholds up toVnodes once every node has been explored - O(V).curPath(and the recursion call stack, whose depth matchescurPath's size) holds up toVnodes along the deepest path - O(V).