Topological sort: Kahn and DFS
Which task can run before another? An arrow A → B means A must come first. Walk through two algorithms on the same directed graph, inspect their different valid orders, then add a cycle and see why a full order becomes impossible.
Video walkthrough
An order that respects every dependency
A topological order contains every vertex exactly once. For every directed edge u → v, u appears before v. Such an order exists exactly when the directed graph is acyclic (a DAG). The arrows may describe build dependencies, course prerequisites or task constraints. This is an ordering problem, not a shortest-path search or a numerical sort.
A graph may have several disconnected parts and isolated vertices; include all of them. An empty graph has the empty order. A self-loop is already a directed cycle. The editor accepts 0–8 vertices and up to 18 distinct directed edges; A B and A -> B mean the same thing. Repeated edges are rejected; weights are not used.
Kahn: take a vertex with no unmet prerequisites
Count incoming edges and enqueue all zero-indegree vertices in A–H order. Remove the front vertex, append it to the output and decrement the degree of each outgoing neighbor. When a neighbor’s degree first reaches zero, append it to the back of the FIFO queue. Newly ready vertices do not jump ahead of vertices already waiting.
The output prefix respects dependencies. At each queue-removal boundary, the queue contains exactly the not-yet-output vertices with no remaining prerequisites. A degree counts incoming edges not yet removed by the scan; while animating one vertex’s outgoing edges, some decrements are still pending. Each vertex enters the queue at most once. Using a head index avoids repeatedly shifting an array.
DFS: finish first, then reverse
DFS uses three states: U (unvisited), A (active), F (finished). Enter a vertex and inspect its outgoing edges. Descend into an unvisited neighbor; skip a finished neighbor. An edge to an active vertex closes a directed cycle along the current stack. The explicit stack stores a vertex and its next outgoing-edge index, so returning to it continues where it stopped.
Append a vertex to postorder only after all its outgoing edges have been checked. Without a cycle, the target of each edge finishes before its source. Reversing the complete postorder therefore puts every source before its targets. Partial postorder is not a topological result. The outer loop starts another DFS for each unvisited vertex, including isolated vertices; the stack shows the current path, not every visited vertex.
One graph, two valid answers
The default graph has A → C, B → C, B → D, C → E, D → E, E → F. Kahn starts with [A, B]. After A, C still depends on B. After B, C and D become ready, in input-edge order. Its result is A, B, C, D, E, F. DFS starts at A, follows C, E, F and records F, E, C, A; then it visits B and D. Reversing the full postorder gives B, D, A, C, E, F. Both answers respect all six edges.
Vertex roots and Kahn’s initial queue follow A–H; neighbors follow the edge-list order. This makes the demo reproducible, but does not promise the lexicographically smallest order or preserve unrelated vertices’ input order. Different answers alone do not show which algorithm is correct. Check every edge. If Kahn has more than one ready vertex at a removal boundary, the DAG has a choice of orders; exactly one choice at every boundary characterizes a unique order.
A cycle prevents a full order
In “Cycle and blocked vertices”, A can be output, but B → C → D → B blocks the remainder. E and F are also blocked downstream of D even though they are not on that cycle. Kahn detects a cycle when the queue is empty before all vertices are output. Its prefix is useful partial progress, not a full topological order and not a list of cycle members.
DFS finds the back edge D → B and reports the actual closed path B → C → D → B. Even if another component was already finished, a cycle anywhere prevents a full order for the entire graph. On a cycle both algorithms report failure; the demo keeps partial state visible and never labels it a complete result.
Time, memory and the animation’s counters
With adjacency lists, both algorithms take O(V + E) time: build the graph once, enter/output each vertex once, scan each outgoing edge at most once. DFS can stop early on a cycle. The adjacency lists occupy O(V + E); algorithm working arrays, queue or explicit stack and result use O(V) additional memory. The sample code assumes valid numbered vertices and an already validated edge list; the editor validates and bounds its input separately.
“Outgoing edges inspected” counts each Kahn decrement or DFS edge examination. Kahn’s initial indegree-counting pass is excluded and explicitly labeled. Queue operations, vertex entries/exits and rendering are not included, so this counter is not a runtime benchmark. One animation tick advances each unfinished algorithm by one event; the completed side holds its last state.
The teaching wrapper stores independent snapshots. Each event copies O(V) state and there are O(V + E) events, so stored history needs O(V(V + E)) memory in addition to the shared input. That is visualization overhead, not the algorithms’ working-space bound. Seeking backwards restores snapshots. Shared controls provide stepping, playback, speed, seeking, full screen, a restorable link and video export.
Executable JavaScript
These functions use vertex indices 0..n−1 (A is 0). They follow the same FIFO, neighbor order, explicit DFS stack, postorder and cycle rules as the demo. A null order means a cycle; an empty array is the valid answer for an empty graph. Run the adjacency helper followed by either function.
Adjacency lists
// Vertices: 0..n-1. Edge [a, b] means a must precede b.
function adjacency(n, edges) {
const next = Array.from({ length: n }, () => []);
for (const [a, b] of edges) next[a].push(b);
return next;
}Kahn
function kahn(n, edges) {
const next = adjacency(n, edges);
const degree = Array(n).fill(0);
for (const [, b] of edges) degree[b]++;
const queue = [], order = [];
for (let v = 0; v < n; v++)
if (degree[v] === 0) queue.push(v);
for (let head = 0; head < queue.length; head++) {
const v = queue[head];
order.push(v);
for (const w of next[v]) {
degree[w]--;
if (degree[w] === 0) queue.push(w);
}
}
return {
order: order.length === n ? order : null,
prefix: order,
blocked: Array.from({ length: n }, (_, v) => v)
.filter(v => degree[v] > 0)
};
}DFS
function topologicalDfs(n, edges) {
const next = adjacency(n, edges);
const color = Array(n).fill(0); // 0 unvisited, 1 active, 2 finished
const stack = [], postorder = [];
function enter(v) {
color[v] = 1;
stack.push({ vertex: v, next: 0 });
}
for (let root = 0; root < n; root++) {
if (color[root] !== 0) continue;
enter(root);
while (stack.length) {
const frame = stack[stack.length - 1], v = frame.vertex;
if (frame.next < next[v].length) {
const w = next[v][frame.next++];
if (color[w] === 1) {
const start = stack.findIndex(f => f.vertex === w);
const cycle = stack.slice(start).map(f => f.vertex);
return { order: null, postorder, cycle: [...cycle, w] };
}
if (color[w] === 0) enter(w);
} else {
stack.pop();
color[v] = 2;
postorder.push(v);
}
}
}
return { order: postorder.slice().reverse(), postorder, cycle: [] };
}Princeton — queue-based topological sort · Princeton — DFS and directed cycles