AlgoFrames

Cycle detection in undirected and directed graphs

Detect cycles in undirected and directed graphs. In a directed graph, DFS colours nodes white, gray and black, and a gray-to-gray edge closes a cycle.

Before you start: Connected components and flood fill.

The idea

Course A must come before B, B before C, and C before A. No student can ever start, because the requirements form a cycle.

Build systems, spreadsheets and course planners all need to find such loops before they try to order the work.

Intuition

DFS gives every node a color: white (plain) is not visited, gray (light blue) is on the current path, black (green) is finished.

Gray nodes are exactly the calls still on the call stack. The side stack shows them as the gray path.

Edge 2→0 (pink) points to gray 0, which is still on the path. Following the path and then this edge returns to 0: a cycle.

Edge 2→3 points to black 3. Node 3 is finished and cannot reach 2, so this edge closes no cycle.

If 3 could reach 2, DFS would have visited 2 from 3 before 3 turned black.

Complexity

Each node turns gray once and black once, and each edge is checked once. The work is O(V + E).

The color array takes O(V) space. On a long path the call stack also holds one frame per gray node.

Very deep graphs can overflow the call stack. An explicit stack of (node, next edge) pairs avoids that.

Pitfalls

With only visited and unvisited, edge 2→3 looks like a cycle because 3 was seen. Directed graphs need gray and black apart.

Visited says only that DFS was there once. Gray says the node is an ancestor right now, which is what a cycle needs.

In an undirected graph, edge 1-0 leads back to the parent 0. Skip the edge you arrived on, or every edge looks like a cycle.

Variations

For undirected graphs, union-find also works. Add edges one by one; edge 2-0 (pink) joins two nodes already in one set, closing a cycle.

Kahn's algorithm removes nodes whose in-degree (in) is 0. Crossed-out 1, 2 and 3 never reach 0, so they sit on a cycle.

Code

Pseudocode

color[all] ← white
visit(u):
  color[u] ← gray
  for each edge u → v
    if color[v] = gray: return true
    if color[v] = white and visit(v): return true
  color[u] ← black
  return false
for each node u
  if color[u] = white and visit(u): return true
return false

Python

WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle(adj):
    color = [WHITE] * len(adj)
    def visit(u):
        color[u] = GRAY
        for v in adj[u]:
            if color[v] == GRAY:
                return True
            if color[v] == WHITE and visit(v):
                return True
        color[u] = BLACK
        return False
    for u in range(len(adj)):
        if color[u] == WHITE and visit(u):
            return True
    return False

JavaScript

const WHITE = 0, GRAY = 1, BLACK = 2;
function hasCycle(adj) {
  const color = new Array(adj.length).fill(WHITE);
  function visit(u) {
    color[u] = GRAY;
    for (const v of adj[u]) {
      if (color[v] === GRAY) return true;
      if (color[v] === WHITE && visit(v)) return true;
    }
    color[u] = BLACK;
    return false;
  }
  for (let u = 0; u < adj.length; u++) {
    if (color[u] === WHITE && visit(u)) return true;
  }
  return false;
}

Java

static final int WHITE = 0, GRAY = 1, BLACK = 2;
boolean hasCycle(List<List<Integer>> adj) {
  int[] color = new int[adj.size()];
  for (int u = 0; u < adj.size(); u++) {
    if (color[u] == WHITE && visit(adj, color, u)) return true;
  }
  return false;
}
boolean visit(List<List<Integer>> adj, int[] color, int u) {
  color[u] = GRAY;
  for (int v : adj.get(u)) {
    if (color[v] == GRAY) return true;
    if (color[v] == WHITE && visit(adj, color, v)) return true;
  }
  color[u] = BLACK;
  return false;
}

Cost at a glance

TimeO(V + E)
SpaceO(V)
InputDirected or undirected graph
OutputWhether a cycle exists, and one cycle

Practice problems (6)

What gray means Warm-up

Cycle detection in a directed graph colors nodes white, gray and black. What does it mean when a node is gray?

The edge that closes the cycle Warm-up

DFS starts at node 0 and tries edges in the order they are listed: 0→1, 0→2, 1→3, 2→3, 3→4, 4→2. Click the edge DFS flags first as closing a cycle.

Detect a cycle Standard

Return true when the graph contains a cycle, and false otherwise. graph.directed says whether edges are one-way. In a directed graph a cycle follows edge directions. In an undirected graph a cycle needs at least three different edges or a self-loop.

Course schedule Standard

There are numCourses courses numbered 0 to numCourses − 1. Each pair [a, b] in prerequisites means course b must be taken before course a. Return true if every course can be finished, and false if the requirements make that impossible.

Spot the bug: every edge is a cycle Standard

This function should report whether an undirected graph has a cycle. It returns true even for the path 0 - 1 - 2. Click the line with the bug, then fix it.

Find the cycle itself Challenge

Given a directed graph, return the nodes of one cycle in order: [c0, c1, …, ck] where every edge c0 → c1, …, ck → c0 exists and no node repeats. A self-loop is the cycle [v]. Return [] when the graph has no cycle. Any correct cycle is accepted.

Related topics

Next on the path: Bipartite check by 2-coloring