1. Three colors
0 unvisited, 1 on the current path (visiting), 2 fully done.
const state = new Array(n).fill(0)Typorithm · medium
Step 1 of 8 · intro card
Graph Algorithms
DFS with three colors: a back edge to a node still on the recursion path proves a directed cycle.
In a directed graph a cycle exists when DFS finds an edge to a node it is still exploring.
Three states distinguish a node on the current path (1) from one already finished (2).
An edge to a state-1 node is a back edge and signals a cycle; state-2 nodes are safe.
0 = unseen, 1 = on path, 2 = done.
Edge to a state-1 node = cycle.
Set state 2 after exploring.
function hasCycle(graph, n) {
const state = new Array(n).fill(0);
function dfs(node) {
state[node] = 1;
for (const next of graph[node]) {
if (state[next] === 1) return true;
if (state[next] === 0 && dfs(next)) return true;
}
state[node] = 2;
return false;
}
for (let node = 0; node < n; node += 1) {
if (state[node] === 0 && dfs(node)) return true;
}
return false;
}Connect each part of the code to the concept before you type.
0 unvisited, 1 on the current path (visiting), 2 fully done.
const state = new Array(n).fill(0)A node is on the active recursion path while its subtree is explored.
state[node] = 1Reaching a node still in state 1 means an edge points back into the current path.
if (state[next] === 1) return trueOnly recurse into untouched nodes and propagate any cycle found.
if (state[next] === 0 && dfs(next)) return trueOnce fully explored, a node can never be part of a new back edge.
state[node] = 2Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputDirected graph · start A · edges A→B:4, A→D:2, B→C:3, B→E:1, D→E:5, E→F:2, C→F:4
Follow temporary values, local state and supporting structures at this step.
Live recursive calls, including their arguments. Returning releases the top frame.
colors · nodes A–F6 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state