Working with Graphs & Trees
What additional feature does this topological sort implementation provide?
function topologicalSort(graph) {
const visited = new Set();
const temp = new Set();
const order = [];
function visit(vertex) {
if (temp.has(vertex)) return false; // cycle
if (visited.has(vertex)) return true;
temp.add(vertex);
for (let neighbor of graph[vertex]) {
if (!visit(neighbor)) return false;
}
temp.delete(vertex);
visited.add(vertex);
order.unshift(vertex);
return true;
}
for (let vertex in graph) {
if (!visited.has(vertex) && !visit(vertex)) {
return null; // graph has cycles
}
}
return order;
}