forked from yangshun/lago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topologicalSort.js
43 lines (36 loc) · 1.01 KB
/
topologicalSort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { Queue } from '../';
/**
* Performs a topological sort on a directed graph.
* @param {Object} graph Node to array of traversable neighboring nodes.
* @return {number[]|string[]} A topological traversal of nodes.
*/
function topologicalSort(graph) {
const nodes = new Map();
const order = [];
const queue = new Queue();
Object.keys(graph).forEach(node => {
nodes.set(node, { in: 0, out: new Set(graph[node]) });
});
Object.keys(graph).forEach(node => {
graph[node].forEach(neighbor => {
nodes.get(neighbor).in += 1;
});
});
nodes.forEach((value, node) => {
if (value.in === 0) {
queue.enqueue(node);
}
});
while (queue.length) {
const node = queue.dequeue();
nodes.get(node).out.forEach(neighbor => {
nodes.get(neighbor).in -= 1;
if (nodes.get(neighbor).in === 0) {
queue.enqueue(neighbor);
}
});
order.push(node);
}
return order.length === Object.keys(graph).length ? order : [];
}
export default topologicalSort;