forked from Yonet/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopological-sort.js
More file actions
61 lines (56 loc) · 1.7 KB
/
topological-sort.js
File metadata and controls
61 lines (56 loc) · 1.7 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
(function (exports) {
'use strict';
var topologicalSort = (function () {
function topologicalSortHelper(node, visited, temp, graph, result) {
temp[node] = true;
var neighbors = graph[node];
for (var i = 0; i < neighbors.length; i += 1) {
var n = neighbors[i];
if (temp[n]) {
throw new Error('The graph is not a DAG');
}
if (!visited[n]) {
topologicalSortHelper(n, visited, temp, graph, result);
}
}
temp[node] = false;
visited[node] = true;
result.push(node);
}
/**
* Topological sort algorithm of a directed acyclic graph.<br><br>
* Time complexity: O(|E| + |V|) where E is a number of edges
* and |V| is the number of nodes.
*
* @public
* @module graphs/others/topological-sort
* @param {Array} graph Adjacency list, which represents the graph.
* @returns {Array} Ordered vertices.
*
* @example
* var topsort =
* require('path-to-algorithms/src/graphs/' +
* 'others/topological-sort').topologicalSort;
* var graph = {
* v1: ['v2', 'v5'],
* v2: [],
* v3: ['v1', 'v2', 'v4', 'v5'],
* v4: [],
* v5: []
* };
* var vertices = topsort(graph); // ['v3', 'v4', 'v1', 'v5', 'v2']
*/
return function (graph) {
var result = [];
var visited = [];
var temp = [];
for (var node in graph) {
if (!visited[node] && !temp[node]) {
topologicalSortHelper(node, visited, temp, graph, result);
}
}
return result.reverse();
};
}());
exports.topologicalSort = topologicalSort;
}(typeof exports === 'undefined' ? window : exports));