const topologicalSort = (adjacency) => {
const inDegree = new Map();
for (const [node, neighbors] of adjacency) {
if (!inDegree.has(node)) inDegree.set(node, 0);
for (const neighbor of neighbors) inDegree.set(neighbor, (inDegree.get(neighbor) ?? 0) + 1);
}
const stack = [...inDegree].filter(([, degree]) => degree === 0).map(([node]) => node);
const res = [...stack];
while (stack.length !== 0) {
const node = stack.pop();
for (const neighbor of adjacency.get(node) ?? []) {
const degree = inDegree.get(neighbor) - 1;
inDegree.set(neighbor, degree);
if (degree === 0) {
res.push(neighbor);
stack.push(neighbor);
}
}
}
return res.length === inDegree.size ? res : null;
};