-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTopologicalOrder.js
More file actions
48 lines (46 loc) · 1.09 KB
/
TopologicalOrder.js
File metadata and controls
48 lines (46 loc) · 1.09 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
// Do a topological sort on a directed acyclic graph.
// The "order" property contains the order.
// The "postorder" property is the order of the reversed digraph.
class TopologicalOrder {
constructor(G, sources = null) {
this.G = G
this.marked = new Array(G.V).fill(false)
this.postorder = []
let dfs = (G, v) => {
this.marked[v] = true
for (let w of G.adj[v]) {
if (!this.marked[w]) {
dfs(G, w)
}
}
this.postorder.push(v)
}
let dfsFromV = v => {
if (!this.marked[v]) {
dfs(G, v)
}
}
if (sources) {
// Visit vertices reachable from each source vertex.
for (let v of sources) {
dfsFromV(v)
}
} else {
// Visit all vertices.
for (let v = 0; v < G.V; v++) {
dfsFromV(v)
}
}
this.order = this.postorder.slice().reverse()
}
reversedVertices() {
return this.postorder
}
reversedValues() {
return this.postorder.map(v => this.G.values[v])
}
dependencyOrder() {
return this.reversedValues()
}
}
module.exports = TopologicalOrder