forked from shellfly/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kosaraju_scc.go
49 lines (43 loc) · 853 Bytes
/
kosaraju_scc.go
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
package algs4
// KosarajuSCC ...
type KosarajuSCC struct {
marked []bool
id []int
count int
}
// NewKosarajuSCC ...
func NewKosarajuSCC(g *Digraph) *KosarajuSCC {
marked := make([]bool, g.V())
id := make([]int, g.V())
k := &KosarajuSCC{marked: marked, id: id}
order := NewDepthFirstOrder(g.Reverse())
for _, v := range order.ReversePost().IntSlice() {
if !k.marked[v] {
k.Dfs(g, v)
k.count++
}
}
return k
}
// Dfs ...
func (k *KosarajuSCC) Dfs(g *Digraph, v int) {
k.marked[v] = true
k.id[v] = k.count
for _, w := range g.Adj(v) {
if !k.marked[w] {
k.Dfs(g, w)
}
}
}
// StronglyConnected ...
func (k *KosarajuSCC) StronglyConnected(v, w int) bool {
return k.id[v] == k.id[w]
}
// ID ...
func (k *KosarajuSCC) ID(v int) int {
return k.id[v]
}
// Count ...
func (k *KosarajuSCC) Count() int {
return k.count
}