-
Notifications
You must be signed in to change notification settings - Fork 1
/
kosaraju.ts
51 lines (45 loc) · 1.07 KB
/
kosaraju.ts
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
import Digraph from './digraph'
import DepthFirstOrder from './depth-first-order'
/**
* 计算强连通分量的 Kosaraju 算法
*
* 给定的两个顶点是强连通的吗?这幅有向图中含有多少个强连通分量
*/
export default class KosarajuSCC {
private marked: boolean[]
private id: number[]
private count: number
constructor(G: Digraph) {
this.marked = []
this.id = []
const order = new DepthFirstOrder(G.reverse())
const reversePost = order.getReversePost()
while (!reversePost.isEmpty()) {
const s = reversePost.pop()
if (!this.marked[s]) {
this.dfs(G, s)
this.count++
}
}
}
private dfs(G: Digraph, v: number) {
this.marked[v] = true
this.id[v] = this.count
const adj = G.getAdj(v)
while (adj.hasNext()) {
const w = adj.next()
if (!this.marked[w]) {
this.dfs(G, w)
}
}
}
stronglyConnected(v: number, w: number) {
return this.id[v] === this.id[w]
}
getId(v: number) {
return this.id[v]
}
getCount() {
return this.count
}
}