Algorithms · Visualized
Cycle Detection (Directed)
Graph Algorithms
Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.
Run a DFS where every node is white (unvisited), gray (on the current recursion path) or black (fully explored). Time: O(V + E) average, O(V + E) worst; space: O(V) for colours and the recursion path.
Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).
Cycle Detection (Directed Graphs)
Graph AlgorithmsRun a DFS where every node is white (unvisited), gray (on the current recursion path) or black (fully explored). The moment an edge leads to a gray node, that node sits somewhere above on the current path — so the path from it back to the current node plus this back edge is a cycle. Black nodes are safe to skip, which keeps the whole check linear.
How Cycle Detection (Directed) Works
- Start a DFS from every still-white node.
- On entering a node, colour it gray and push it onto the current path.
- For each outgoing edge: if the target is gray, a back edge — report the cycle and stop.
- If the target is white, recurse into it; if it is black, skip it — it was already proven cycle-free.
- When all edges of a node are handled, colour it black and backtrack.
Cycle Detection (Directed) Worked Example
Input: {graph: A→B, A→C, B→D, C→D, D→E, E→B, start: A}
A gray → B gray → D gray → E gray → E's edge to B: B is gray and sits on the current path [A, B, D, E] → back edge! The cycle is B → D → E → B. Without the E→B edge the same DFS would blacken every node and conclude DAG.
def has_cycle(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
color = [0] * n # 0 white, 1 gray, 2 black
def go(u):
color[u] = 1
for v in adj[u]:
if color[v] == 1: # back edge into the path
return True
if color[v] == 0 and go(v):
return True
color[u] = 2 # fully processed
return False
return any(color[s] == 0 and go(s) for s in range(n))Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Cycle Detection (Directed) Time & Space Complexity
When to Use Cycle Detection (Directed)
- Deadlock and dependency-cycle detection in build tools, package managers and databases.
- Precondition check before topological sorting; detecting re-entrant state machines.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.