progress

~/problems / Graphs / Cycle detection

Does a directed graph have a cycle?

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write has_cycle(n, edges) -> bool. The graph is directed, with nodes 0 .. n-1; each pair (a, b) is an edge from a to b. Return True if some path leaves a node and comes back to it.

has_cycle(4, [(0, 1), (1, 2), (2, 0), (2, 3)])   # True    0 -> 1 -> 2 -> 0
has_cycle(4, [(0, 1), (0, 2), (1, 3), (2, 3)])   # False   two routes to 3 is not a cycle
Two directed graphs: on the left a loop 0 to 1 to 2 back to 0 with an exit to 3; on the right a diamond where two routes reach node 3 but no path returns to its start.

The trap is the second example: a plain "seen" set says you revisited 3, but that isn't a loop. A self-loop (a, a) is a cycle. The graph may be disconnected, so start a search from every unfinished node.

Up to 200 nodes and 1000 edges, so plain recursion is fine.

Show hint

DFS with three colours: white (unvisited), grey (on the current path), black (fully explored). Reaching a grey node means a cycle; a black one is harmless.

Topic: Cycle detection. Visited / on-stack sets; symlinks, CNAMEs, instruction loops.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc