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 Algorithms

Run 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

  1. Start a DFS from every still-white node.
  2. On entering a node, colour it gray and push it onto the current path.
  3. For each outgoing edge: if the target is gray, a back edge — report the cycle and stop.
  4. If the target is white, recurse into it; if it is black, skip it — it was already proven cycle-free.
  5. 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.

Cycle Detection (Directed)O(V + E)
DFS with white/gray/black colours — a back edge into a gray node is a cycle.
1
0
0
1
0
2
0
3
0
4
0
5
AGRAYBwhiteCwhiteDwhiteEwhiteFwhite
pathA
colors0=white 1=gray 2=black
Step 1 / 9
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Enter A → mark GRAY (on the current path). Path: [A].
Python · Graph Algorithms in Code
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

BestO(V + E)
AverageO(V + E)
WorstO(V + E)
SpaceO(V) for colours and the recursion path

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.