Cycle Detection In Directed Graphs
Detect directed cycles with three-color depth-first search, returning a concrete closed path for diagnostics or null for a DAG.
Code
const WHITE = 0;
const GRAY = 1;
const BLACK = 2;
export function findCycle(
graph: ReadonlyMap<string, readonly string[]>,
): string[] | null {
const state = new Map<string, number>();
const stack: string[] = [];
const visit = (node: string): string[] | null => {
state.set(node, GRAY);
stack.push(node);
for (const neighbor of graph.get(node) ?? []) {
const color = state.get(neighbor) ?? WHITE;
if (color === GRAY) {
const start = stack.indexOf(neighbor);
return [...stack.slice(start), neighbor];
}
if (color === WHITE) {
const cycle = visit(neighbor);
if (cycle) return cycle;
}
}
stack.pop();
state.set(node, BLACK);
return null;
};
for (const node of graph.keys()) {
if ((state.get(node) ?? WHITE) === WHITE) {
const cycle = visit(node);
if (cycle) return cycle;
}
}
return null;
}How it works
Cycle Detection In Directed Graphs keeps everything in the functions visit and findCycle.
The structure is a loop within a loop: for (const neighbor of graph.get(node) ?? []) outside, for (const node of graph.keys()) inside.
The result is a fresh construction, so callers can keep their originals.
Points of care
- The guard
cycleshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The main signature reads export function findCycle( graph: ReadonlyMap<string, readonly string[]>, )
findCycle is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
for (const neighbor of graph.get(node) ?? []) {
const color = state.get(neighbor) ?? WHITE;
if (color === GRAY) {
const start = stack.indexOf(neighbor);
return [...stack.slice(start), neighbor];
}
if (color === WHITE) {
const cycle = visit(neighbor);
if (cycle) return cycle;
}
}
if ((state.get(node) ?? WHITE) === WHITE) {
const cycle = visit(node);
if (cycle) return cycle;
}
const state = new Map<string, number>();
Interactive Tools for This Topic
FAQ
- Does `findCycle` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `visit`, `findCycle` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.