Lesson 10 · Problem-solving methods

Directed Graph Cycle Detection

A directed graph has a cycle exactly when a depth-first search finds an edge leading to a vertex that is still on its current path. Three vertex states make that test possible, and a parent array turns the hit into the cycle itself.

Directed Graph Cycle Detection concept diagramA directed graph with vertices 0 to 5 during a depth-first search. Tree edges 0 to 1, 1 to 2, 0 to 3, 3 to 4, 4 to 5. Forward edge 0 to 2 and cross edge 3 to 2 point at finished vertices and are harmless. The back edge 5 to 3 points at a vertex still on the current path 0, 3, 4, 5, which closes the cycle 3, 4, 5.012345blue: on the current path (grey) · green: finished (black)Tree edgeunvisited target: move into itForward edgeto a finished descendant: harmlessCross edgeto a finished vertex elsewhere: harmlessBack edgeto a vertex on the path: a cycleEdge u → v, sorted by the state of vcycle closed by 5 → 3:3 → 4 → 5 → 3
1

What Counts as a Cycle When Edges Have Direction

A directed cycle is a walk that follows the arrows and comes back to its start: a → b → c → a. Every edge must be used in its own direction. Two edges a → b and b → a already form a cycle, and so does a single edge a → a.

Most directed graphs in practice are dependency graphs: task b needs task a, module x imports module y, course 201 requires course 101. A cycle there means a set of things that all wait on each other, so nothing in it can ever start. That is why circular dependency detection is the first check a build tool, a package manager or a spreadsheet runs.

The trap is that meeting an old vertex again proves nothing. In a diamond, a → b → d and a → c → d, the search reaches d twice without any cycle. The question is not 'have I seen this vertex?' but 'is this vertex still on the path I am walking?'. The cycle detection overview puts this next to the undirected case, where the answer is different.

  • Cycle: follow the arrows and return to the start
  • Two opposite edges, or one edge to itself, already count
  • A vertex reached twice is only a cycle if it is still on the current path
2

Three States and Four Kinds of Edge

The standard answer is white grey black DFS. Every vertex starts unvisited (white). It turns grey the moment the search enters it, and black once every edge out of it has been followed. At any moment, the grey vertices are exactly the recursion stack: the path from the start to where the search stands.

When the search looks along an edge u → v, the state of v sorts the edge into one of four kinds. The diagram above shows all four in one graph.

  • Tree edge: v is white. The search moves to v; these edges form the DFS tree
  • Back edge: v is grey, so v is u itself or an ancestor of u on the current path. This edge closes a cycle
  • Forward edge: v is black and a descendant of u, reached earlier by another branch. Harmless
  • Cross edge: v is black and in a part of the search already finished elsewhere. Harmless
3

Why a Back Edge Means a Cycle, and Only Then

If the search finds u → v with v grey, then v is on the stack below u, so the tree edges already give a path v → … → u. Add the edge u → v and you are back at v. That is a cycle.

The other direction matters more, because it says the test never misses one. Suppose a cycle exists, and let v be the first of its vertices the search enters. At that moment every other vertex on the cycle is white and reachable from v along the cycle. DFS does not finish v until everything reachable through white vertices has been entered, so the vertex u just before v on the cycle is entered while v is still grey. When u looks along u → v, it finds v grey: a back edge.

Forward and cross edges point at black vertices. A black vertex has finished without the search reporting anything. If some path led from it back to a vertex on the current path, the search from it would have met that grey vertex and stopped with a cycle. So those edges can be skipped safely.

  • Time O(V + E): each vertex is entered once and each edge is looked at once
  • Space O(V) for the states, the parents and the stack
  • Start a fresh search from every vertex still white, or a cycle in an unreached part is missed
Key reference

Terms, operations, and practical uses

Key terms

  • Grey vertexEntered but not finished: it is on the current DFS path.
  • Back edgeAn edge to a grey vertex. It exists exactly when the graph has a cycle.
  • Forward and cross edgesEdges to black vertices. They never close a cycle.
  • DAGA directed acyclic graph: the case where the search finds no back edge.
Implementation

Code in Python, C++ and Java

WHITE, GREY, BLACK = 0, 1, 2


def find_cycle(n, edges):
    graph = [[] for _ in range(n)]
    for u, v in edges:
        graph[u].append(v)
    colour = [WHITE] * n
    parent = [-1] * n

    def dfs(u):
        colour[u] = GREY
        for v in graph[u]:
            if colour[v] == GREY:
                cycle, x = [], u
                while x != v:
                    cycle.append(x)
                    x = parent[x]
                cycle.append(v)
                cycle.reverse()
                return cycle + [v]
            if colour[v] == WHITE:
                parent[v] = u
                found = dfs(v)
                if found:
                    return found
        colour[u] = BLACK
        return None

    for start in range(n):
        if colour[start] == WHITE:
            found = dfs(start)
            if found:
                return found
    return None


def show(name, n, edges):
    cycle = find_cycle(n, edges)
    print(name + ":", " -> ".join(map(str, cycle)) if cycle else "no cycle")


tasks = [(0, 1), (1, 2), (0, 3), (3, 2), (3, 4), (4, 5), (5, 3)]
show("tasks", 6, tasks)
show("without 5 -> 3", 6, tasks[:-1])
show("diamond", 4, [(0, 1), (0, 2), (1, 3), (2, 3)])
show("self-loop", 3, [(0, 1), (1, 2), (2, 2)])
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;

enum { WHITE, GREY, BLACK };

struct Finder {
    vector<vector<int>> graph;
    vector<int> colour, parent, cycle;

    Finder(int n, const vector<pair<int, int>>& edges) : graph(n), colour(n, WHITE), parent(n, -1) {
        for (auto [u, v] : edges) graph[u].push_back(v);
    }

    bool dfs(int u) {
        colour[u] = GREY;
        for (int v : graph[u]) {
            if (colour[v] == GREY) {
                for (int x = u; x != v; x = parent[x]) cycle.push_back(x);
                cycle.push_back(v);
                reverse(cycle.begin(), cycle.end());
                cycle.push_back(v);
                return true;
            }
            if (colour[v] == WHITE) {
                parent[v] = u;
                if (dfs(v)) return true;
            }
        }
        colour[u] = BLACK;
        return false;
    }

    bool run() {
        for (int s = 0; s < (int)graph.size(); s++)
            if (colour[s] == WHITE && dfs(s)) return true;
        return false;
    }
};

void show(const string& name, int n, const vector<pair<int, int>>& edges) {
    Finder f(n, edges);
    cout << name << ": ";
    if (!f.run()) { cout << "no cycle\n"; return; }
    for (size_t i = 0; i < f.cycle.size(); i++) cout << (i ? " -> " : "") << f.cycle[i];
    cout << "\n";
}

int main() {
    vector<pair<int, int>> tasks = {{0, 1}, {1, 2}, {0, 3}, {3, 2}, {3, 4}, {4, 5}, {5, 3}};
    show("tasks", 6, tasks);
    show("without 5 -> 3", 6, vector<pair<int, int>>(tasks.begin(), tasks.end() - 1));
    show("diamond", 4, {{0, 1}, {0, 2}, {1, 3}, {2, 3}});
    show("self-loop", 3, {{0, 1}, {1, 2}, {2, 2}});
}
import java.util.*;

public class Main {
    static final int WHITE = 0, GREY = 1, BLACK = 2;
    static List<List<Integer>> graph;
    static int[] colour, parent;
    static List<Integer> cycle;

    static boolean dfs(int u) {
        colour[u] = GREY;
        for (int v : graph.get(u)) {
            if (colour[v] == GREY) {
                for (int x = u; x != v; x = parent[x]) cycle.add(x);
                cycle.add(v);
                Collections.reverse(cycle);
                cycle.add(v);
                return true;
            }
            if (colour[v] == WHITE) {
                parent[v] = u;
                if (dfs(v)) return true;
            }
        }
        colour[u] = BLACK;
        return false;
    }

    static List<Integer> findCycle(int n, int[][] edges) {
        graph = new ArrayList<>();
        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
        for (int[] e : edges) graph.get(e[0]).add(e[1]);
        colour = new int[n];
        parent = new int[n];
        Arrays.fill(parent, -1);
        cycle = new ArrayList<>();
        for (int s = 0; s < n; s++)
            if (colour[s] == WHITE && dfs(s)) return cycle;
        return null;
    }

    static void show(String name, int n, int[][] edges) {
        List<Integer> c = findCycle(n, edges);
        StringBuilder sb = new StringBuilder(name + ": ");
        if (c == null) sb.append("no cycle");
        else for (int i = 0; i < c.size(); i++) sb.append(i > 0 ? " -> " : "").append(c.get(i));
        System.out.println(sb);
    }

    public static void main(String[] args) {
        int[][] tasks = {{0, 1}, {1, 2}, {0, 3}, {3, 2}, {3, 4}, {4, 5}, {5, 3}};
        show("tasks", 6, tasks);
        show("without 5 -> 3", 6, Arrays.copyOf(tasks, 6));
        show("diamond", 4, new int[][]{{0, 1}, {0, 2}, {1, 3}, {2, 3}});
        show("self-loop", 3, new int[][]{{0, 1}, {1, 2}, {2, 2}});
    }
}
Watch it run

Step through it

Running on edges 0→1, 1→2, 0→3, 3→2, 3→4, 4→5, 5→3

edge u → v: what is v's state?012345ON THE PATH(empty)bottom = startunvisited · blue: on the path · green: finishedLook for an edge into a blue vertex.
Step 1

Six tasks, seven dependencies

An edge u → v means u must look at v. Every vertex starts unvisited. During the search a vertex is grey (blue here) while it is on the current path and black (green) once everything reachable from it has been explored. The stack on the right is that path.

Output
1 / 13
4

How to Print the Cycle

  1. Start at u and add it to a list
  2. Move to parent[u], add it, and repeat until you reach v
  3. Add v, reverse the list, and append v once more to close the loop
  4. For a self-loop (u = v) the list is just v → v

A yes or no is rarely enough; the user wants to see which tasks block each other. To print the cycle, record parent[v] = u whenever a tree edge u → v is taken. When the back edge u → v appears, the cycle is the stack from v up to u.

  • The tracer's graph gives 3 → 4 → 5 → 3: the stack read from vertex 3 upward
  • This prints one cycle, the first found. Listing every cycle can take exponential time, because a dense graph has that many
5

Running It Without Recursion

A chain of 100,000 dependencies means a recursion 100,000 calls deep, beyond Python's default limit and risky in C++ or Java. An explicit stack fixes this. Push pairs (vertex, index of the next edge to try). Look at the top pair: if it has edges left, examine the next one and push its target when white; if it has none, paint it black and pop it.

The common bug is painting a vertex black, or marking it visited, when it is pushed instead of when it is popped. Then the grey state disappears, every revisit looks the same, and the diamond is reported as a cycle again.

  • Grey when the vertex is pushed, black when it is popped
  • Same O(V + E) cost; memory moves from the call stack to the heap
6

The In-Degree Alternative

A second method needs no DFS at all. Count the incoming edges of every vertex, repeatedly remove a vertex whose count is zero, and lower the counts of its targets. This is the queue-based topological sort. If every vertex comes out, the graph is acyclic.

If some vertices never reach zero, the graph has a cycle, but those leftovers are the cycle plus everything downstream of it, not the cycle alone. Use this method when you only need a yes or no, or when you need an order anyway; use the three-state DFS when you must show the loop.

  • No recursion, O(V + E)
  • Leftover vertices: a cycle exists, but they include its downstream vertices too
7

Where It Is Used, and Problems to Practise

Operating systems look for a cycle in the wait-for graph (process a waits for a lock held by b) to detect deadlock. Build systems such as make and package managers refuse to run with a circular dependency. Spreadsheets flag a formula that refers back to its own cell. Course planners check that prerequisites can be met at all.