Skip to content

Commit 432efa1

Browse files
committed
Add topological sort
1 parent 4fee254 commit 432efa1

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/graphs/others/topological-sort.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
var topologicalSort = (function () {
2+
'use strict';
3+
4+
function topologicalSortHelper(node, visited, temp, graph, result) {
5+
temp[node] = true;
6+
var neighbors = graph[node];
7+
for (var i = 0; i < neighbors.length; i += 1) {
8+
var n = neighbors[i];
9+
if (temp[n]) {
10+
throw new Error('The graph is not a DAG');
11+
}
12+
if (!visited[n]) {
13+
topologicalSortHelper(n, visited, temp, graph, result);
14+
}
15+
}
16+
temp[node] = false;
17+
visited[node] = true;
18+
result.push(node);
19+
}
20+
21+
return function (graph) {
22+
var result = [],
23+
visited = [],
24+
temp = [];
25+
for (var node in graph) {
26+
if (!visited[node] && !temp[node]) {
27+
topologicalSortHelper(node, visited, temp, graph, result);
28+
}
29+
}
30+
return result.reverse();
31+
};
32+
}());
33+
34+
var graph = {
35+
'0': ['1', '2'],
36+
'1': ['2', '4'],
37+
'2': ['3'],
38+
'3': [],
39+
'4': ['5', '6'],
40+
'5': [],
41+
'6': ['3']
42+
};
43+
44+
console.log(topologicalSort(graph));

0 commit comments

Comments
 (0)