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 Approaches
DFS
O(V + E)O(V + E)
BFS
O(V + E)O(V + E)
FIG. UNDIRECTED GRAPH CYCLE● INTERACTIVE
visualization loads as you reach it
Directed
Directed Graph Cycle
Medium·
2 Approaches
DFS
O(V + 2E)O(3V + E)
BFS - Khan's algorithm
O(2V + 2E)O(3V + E)
FIG. DIRECTED GRAPH CYCLE● INTERACTIVE
visualization loads as you reach it