Graph DFS Topological Sort Typed
Perform topological sort on a typed DAG using DFS with cycle detection via tri-color marking.
Code
function topologicalSort(graph: Map<string, string[]>): string[] {
const WHITE = 0, GRAY = 1, BLACK = 2;
const color = new Map<string, number>();
const result: string[] = [];
for (const n of graph.keys()) color.set(n, WHITE);
function dfs(node: string): void {
const c = color.get(node)!;
if (c === GRAY) throw new Error("cycle at " + node);
if (c === BLACK) return;
color.set(node, GRAY);
for (const neighbor of graph.get(node) ?? []) dfs(neighbor);
color.set(node, BLACK); result.push(node);
}
for (const n of graph.keys()) if (color.get(n) === WHITE) dfs(n);
return result.reverse();
}Report a problem with this exampleOpens a pre-filled issue on GitHub.