Learn / Graphs

Cycle detection

In an undirected graph, an edge whose two ends are already connected closes a cycle: a disjoint-set check finds it. In a directed graph, a cycle is an edge back to a vertex still on the current DFS path, found with three colours (unvisited, on the path, finished), or by Kahn's algorithm failing to process every vertex.

How to recognise it

  • Can the graph contain a loop?
  • Is a graph a tree (connected, no cycle)?
  • Which vertices can never reach a cycle?

Undirected and directed

undirected: for (u, v) in edges: if find(u) == find(v): cycle; else union(u, v)
directed:   dfs(u): state[u] = on path
                    for v in adj[u]: if state[v] == on path: cycle
                                     if state[v] == new: dfs(v)
                    state[u] = done

Vertices, edges, adjacency lists and the other words used here are on the Structures page.

Common mistakes

  • Using the undirected parent check on a directed graph.
  • Calling a graph a tree without checking it is connected.

Problems

0 of 4 solved

Check yourself

A tree on n vertices has how many edges?

In directed DFS, which edge shows a cycle?

A node is 'eventually safe' when?