Cycle detection
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Cycle detection checks whether following the links in a network can bring you back to where you started. Cycles are harmless in friendships but disastrous in things that must happen in order, so spotting them early prevents endless loops.
Practical use cases
- Web app: Circular category parents. An admin sets category A as parent of B, and later B as parent of A by mistake. The menu code then loops forever and the page times out. A cycle check at save time rejects the change with "this would create a loop".
- Web app: Task dependencies in a project tool. In a Trello-style board, task 3 is blocked by task 5 and task 5 by task 3. Nobody can ever start. When a user adds a dependency, the app checks for a cycle and shows an error instead of silently saving an impossible plan.
- Web app: Spreadsheet formulas. An online sheet lets cell A1 use B1, and B1 use A1. The engine must notice the circular reference and show a warning, otherwise the browser hangs recalculating.
- System: Package managers and deadlocks. Installers refuse packages that require each other in a ring, and databases look for transactions waiting on each other in a circle, which is a deadlock, then cancel one of them. In each of these, the check is the same walk around the links, remembering where you have already been on the current trail, and flagging a repeat.
The story: The Roundabout That Never Ends
Kabir took an auto-rickshaw in an unfamiliar town. The driver promised a shortcut, took three turns, and Kabir saw the same sweet shop again. "We are going round in circles!" The driver had unknowingly followed a cycle: a path that returns to its own start.
Mira thought about how to spot this in a map. "While we walk, we chalk each junction we pass. If we ever reach a chalked junction by a new road, we are going round."
But careful: when you step from the sweet shop to the temple, the sweet shop is chalked and you can see it right behind you. That is not a cycle, it is just the road you came on. Mira added a rule: remember the junction you came from and ignore only that one.
This chalk-and-parent trick finds a cycle in an undirected graph. For one-way streets (directed graph) the rule changes slightly: you are in trouble only if you meet a junction that is still open on your current path.
How to spot this problem, and where you need it
Something depends on, contains or waits for something else, and a mistake could make the chain loop back on itself, causing endless loops, frozen pages, or tasks that can never start.
Signs you need it
- Users can set a "parent", "depends on", "blocked by", "reports to" or "requires" field pointing to another record of the same kind.
- A page hangs or a recursive function crashes with "maximum call stack" or "maximum execution time" only for certain data.
- The problem asks "is this a valid order?" or "can this ever finish?".
Where to use it in a project
- Validation when saving a parent category, a manager, or a task dependency, before the loop reaches the database.
- A build, migration or job scheduler that must confirm its dependency list can actually be completed.
The solution
Walk the links with DFS and track the nodes on the current path. If you reach a node that is already on the current path, you found a cycle. In an undirected network, ignore the single parent you just came from. For a quick check before saving a new link A to B, ask whether B can already reach A; if yes, adding the link would create a loop, so reject it.
Payoff: Before: one bad dropdown choice hangs the whole category page. After: the form says "this creates a loop" in a fraction of a second and nothing is saved.
Explain it like I am 8
Imagine walking in a park and dropping a breadcrumb at every spot. If you ever step onto a spot that already has a crumb and it is not the one you just left, then you walked in a circle!
How it works, step by step
- Walk with DFS and remember each vertex's parent (the vertex you came from).
- Look at every neighbour. If it is unvisited, dive into it with the current vertex as its parent.
- If it is visited and it is the parent, ignore it (that is the road you just used).
- If it is visited and not the parent, you have found a cycle. Stop and report it.
- For directed graphs, colour vertices: white (new), grey (on the current path), black (finished). Meeting a grey vertex means a cycle.
The code in four languages
PHP
<?php
// UNDIRECTED: DFS, ignore only the parent edge.
function hasCycleUndirected(array $graph): bool {
$seen = [];
$dfs = function (string $u, ?string $parent) use (&$dfs, &$seen, $graph): bool {
$seen[$u] = true;
foreach ($graph[$u] as $v) {
if (!isset($seen[$v])) {
if ($dfs($v, $u)) return true;
} elseif ($v !== $parent) {
return true; // met an old vertex by a different road
}
}
return false;
};
foreach (array_keys($graph) as $s) {
if (!isset($seen[$s]) && $dfs($s, null)) return true;
}
return false;
}
// DIRECTED: 0 = new, 1 = on the current path, 2 = finished.
function hasCycleDirected(array $graph): bool {
$state = [];
$dfs = function (string $u) use (&$dfs, &$state, $graph): bool {
$state[$u] = 1;
foreach ($graph[$u] as $v) {
$s = $state[$v] ?? 0;
if ($s === 1) return true; // back to a vertex still open
if ($s === 0 && $dfs($v)) return true;
}
$state[$u] = 2;
return false;
};
foreach (array_keys($graph) as $s) {
if (($state[$s] ?? 0) === 0 && $dfs($s)) return true;
}
return false;
}
$loop = ['A'=>['B'], 'B'=>['A','C','D'], 'C'=>['B','D'], 'D'=>['C','B']];
$line = ['A'=>['B'], 'B'=>['A','C'], 'C'=>['B']];
echo 'Loop graph: ' . (hasCycleUndirected($loop) ? 'cycle' : 'no cycle') . "\n";
echo 'Line graph: ' . (hasCycleUndirected($line) ? 'cycle' : 'no cycle') . "\n";
echo 'Directed A->B->C->A: ' . (hasCycleDirected(['A'=>['B'], 'B'=>['C'], 'C'=>['A']]) ? 'cycle' : 'no cycle') . "\n";
echo 'Directed A->B, A->C, B->C: ' . (hasCycleDirected(['A'=>['B','C'], 'B'=>['C'], 'C'=>[]]) ? 'cycle' : 'no cycle') . "\n";JavaScript
// UNDIRECTED: DFS, ignore only the parent edge.
function hasCycleUndirected(graph) {
const seen = new Set();
function dfs(u, parent) {
seen.add(u);
for (const v of graph[u]) {
if (!seen.has(v)) {
if (dfs(v, u)) return true;
} else if (v !== parent) {
return true; // met an old vertex by a different road
}
}
return false;
}
for (const s of Object.keys(graph)) {
if (!seen.has(s) && dfs(s, null)) return true;
}
return false;
}
// DIRECTED: 0 = new, 1 = on the current path, 2 = finished.
function hasCycleDirected(graph) {
const state = {};
function dfs(u) {
state[u] = 1;
for (const v of graph[u]) {
const s = state[v] || 0;
if (s === 1) return true; // back to a vertex still open
if (s === 0 && dfs(v)) return true;
}
state[u] = 2;
return false;
}
for (const s of Object.keys(graph)) {
if (!state[s] && dfs(s)) return true;
}
return false;
}
const loop = { A: ['B'], B: ['A','C','D'], C: ['B','D'], D: ['C','B'] };
const line = { A: ['B'], B: ['A','C'], C: ['B'] };
console.log('Loop graph: ' + (hasCycleUndirected(loop) ? 'cycle' : 'no cycle'));
console.log('Line graph: ' + (hasCycleUndirected(line) ? 'cycle' : 'no cycle'));
console.log('Directed A->B->C->A: ' + (hasCycleDirected({ A: ['B'], B: ['C'], C: ['A'] }) ? 'cycle' : 'no cycle'));
console.log('Directed A->B, A->C, B->C: ' + (hasCycleDirected({ A: ['B','C'], B: ['C'], C: [] }) ? 'cycle' : 'no cycle'));Java
import java.util.*;
public class Main {
// UNDIRECTED: DFS, ignore only the parent edge.
static boolean hasCycleUndirected(Map<String, List<String>> graph) {
Set<String> seen = new HashSet<>();
for (String s : graph.keySet()) {
if (!seen.contains(s) && dfsUndirected(graph, s, null, seen)) return true;
}
return false;
}
static boolean dfsUndirected(Map<String, List<String>> graph, String u, String parent, Set<String> seen) {
seen.add(u);
for (String v : graph.get(u)) {
if (!seen.contains(v)) {
if (dfsUndirected(graph, v, u, seen)) return true;
} else if (!v.equals(parent)) {
return true; // met an old vertex by a different road
}
}
return false;
}
// DIRECTED: 0 = new, 1 = on the current path, 2 = finished.
static boolean hasCycleDirected(Map<String, List<String>> graph) {
Map<String, Integer> state = new HashMap<>();
for (String s : graph.keySet()) {
if (state.getOrDefault(s, 0) == 0 && dfsDirected(graph, s, state)) return true;
}
return false;
}
static boolean dfsDirected(Map<String, List<String>> graph, String u, Map<String, Integer> state) {
state.put(u, 1);
for (String v : graph.get(u)) {
int s = state.getOrDefault(v, 0);
if (s == 1) return true; // back to a vertex still open
if (s == 0 && dfsDirected(graph, v, state)) return true;
}
state.put(u, 2);
return false;
}
static String verdict(boolean cycle) {
return cycle ? "cycle" : "no cycle";
}
public static void main(String[] args) {
var loop = Map.of("A", List.of("B"), "B", List.of("A", "C", "D"),
"C", List.of("B", "D"), "D", List.of("C", "B"));
var line = Map.of("A", List.of("B"), "B", List.of("A", "C"), "C", List.of("B"));
System.out.println("Loop graph: " + verdict(hasCycleUndirected(loop)));
System.out.println("Line graph: " + verdict(hasCycleUndirected(line)));
System.out.println("Directed A->B->C->A: "
+ verdict(hasCycleDirected(Map.of("A", List.of("B"), "B", List.of("C"), "C", List.of("A")))));
System.out.println("Directed A->B, A->C, B->C: "
+ verdict(hasCycleDirected(Map.of("A", List.of("B", "C"), "B", List.of("C"), "C", List.of()))));
}
}Go
package main
import (
"fmt"
"sort"
)
type Graph map[string][]string
func (g Graph) names() []string {
out := make([]string, 0, len(g))
for v := range g {
out = append(out, v)
}
sort.Strings(out)
return out
}
// UNDIRECTED: DFS, ignore only the parent edge. ("" means "no parent".)
func hasCycleUndirected(graph Graph) bool {
seen := map[string]bool{}
var dfs func(u, parent string) bool
dfs = func(u, parent string) bool {
seen[u] = true
for _, v := range graph[u] {
if !seen[v] {
if dfs(v, u) {
return true
}
} else if v != parent {
return true // met an old vertex by a different road
}
}
return false
}
for _, s := range graph.names() {
if !seen[s] && dfs(s, "") {
return true
}
}
return false
}
// DIRECTED: 0 = new, 1 = on the current path, 2 = finished.
func hasCycleDirected(graph Graph) bool {
state := map[string]int{}
var dfs func(u string) bool
dfs = func(u string) bool {
state[u] = 1
for _, v := range graph[u] {
s := state[v]
if s == 1 {
return true // back to a vertex still open
}
if s == 0 && dfs(v) {
return true
}
}
state[u] = 2
return false
}
for _, s := range graph.names() {
if state[s] == 0 && dfs(s) {
return true
}
}
return false
}
func verdict(cycle bool) string {
if cycle {
return "cycle"
}
return "no cycle"
}
func main() {
loop := Graph{"A": {"B"}, "B": {"A", "C", "D"}, "C": {"B", "D"}, "D": {"C", "B"}}
line := Graph{"A": {"B"}, "B": {"A", "C"}, "C": {"B"}}
fmt.Println("Loop graph: " + verdict(hasCycleUndirected(loop)))
fmt.Println("Line graph: " + verdict(hasCycleUndirected(line)))
fmt.Println("Directed A->B->C->A: " + verdict(hasCycleDirected(Graph{"A": {"B"}, "B": {"C"}, "C": {"A"}})))
fmt.Println("Directed A->B, A->C, B->C: " + verdict(hasCycleDirected(Graph{"A": {"B", "C"}, "B": {"C"}, "C": {}})))
}Time: O(V + E) · Extra space: O(V). One DFS over the whole graph. A cycle can also stop the search early.
Watch out for
- In an undirected graph, treating the parent as a cycle. Every edge would look like a loop of two!
- In a directed graph, using the parent trick. Two arrows reaching the same vertex from different sides (A→B, A→C, B→C) are not a cycle.
- Starting DFS from only one vertex. A cycle may hide in a different component.
Quick check
- DFS in an undirected graph meets a visited vertex that is NOT the parent. What does that mean?
- Nothing special
- A cycle exists
- The graph is disconnected
- Why must undirected DFS ignore the parent?
- The parent has no edges
- To save time
- The edge back to the parent is just the road we arrived on
- A directed graph has A→B, A→C and B→C. Is there a cycle?
- No, you can never return to a vertex
- Yes, C is reached twice
- Only if you start from C