Command Palette

Search for a command to run...

Module 23

Cycle Detection

Find loops in graphs: parent tracking and union-find for undirected graphs, three-colour DFS for directed graphs, and functional graphs.

Intermediate 3 lessons 6 problems ~35 min of lessons

A cycle is a path that comes back to where it started. Detecting one answers practical questions: can these courses be finished (no circular prerequisites), is this network a tree, which connection is redundant, will this process loop forever?

Undirected and directed graphs need different checks. In an undirected graph, meeting any already-visited node other than your parent means a cycle. In a directed graph, that isn't enough: you must know whether the node is still on the current DFS path, which is what the three-colour method tracks.

Best after: Depth-First Search

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Tree = n − 1 edges and no cycle (which together imply connected).

  2. The first edge that joins two already-connected nodes is the one that closed the cycle.

  3. Can all tasks finish? Only if the dependency graph has no directed cycle.

  4. Colours as results: a node is safe when every path from it ends, i.e. it can't reach a cycle.

  5. Undirected cycle detection on an implicit grid graph, remembering the parent cell.

  6. Functional graphs: walk with timestamps to measure each cycle once.