Line up a DAG so every arrow points forward — repeatedly output a node with no remaining prerequisites (Kahn's algorithm).
A topological sort lines up the vertices of a directed acyclic graph (DAG) so that every arrow points forward — if there's an edge A → B, then A appears before B. It's the answer to any 'what order can I do these in?' question where some tasks must precede others: course prerequisites, build dependencies, spreadsheet recalculation.
A → B → A would demand that A come before B *and* B before A — impossible. So a topological sort either succeeds or proves the graph has a cycle.The key number is each vertex's in-degree: how many arrows point *into* it — its count of unmet prerequisites. A vertex with in-degree 0 has nothing blocking it, so it's safe to output now. Output it, remove its outgoing edges (which lowers its neighbours' in-degrees), and that may free up new zero-in-degree vertices.
0 vertices into a queue — they have no prerequisites.0, enqueue it.function kahn(V, adj) {
const indeg = Array(V).fill(0);
for (let u = 0; u < V; u++) for (const v of adj[u]) indeg[v]++;
const queue = [];
for (let u = 0; u < V; u++) if (indeg[u] === 0) queue.push(u);
const order = [];
while (queue.length) {
const u = queue.shift();
order.push(u);
for (const v of adj[u]) if (--indeg[v] === 0) queue.push(v);
}
return order.length === V ? order : null; // null => a cycle exists
}V, some vertices never reached in-degree 0 — they're tangled in a cycle that never releases them. So Kahn's algorithm tells you *for free* whether the graph was acyclic at all.