Debian Codegraph @

weak.go

raw symbols SCIP
1 package graph
2
3 // Connected tells if g has exactly one (weakly) connected component.
4 func Connected(g Iterator) bool {
5 _, count := components(g)
6 return count == 1
7 }
8
9 // Components produces a partition of g's vertices into its
10 // (weakly) connected components.
11 func Components(g Iterator) [][]int {
12 sets, count := components(g)
13
14 m := make([][]int, g.Order())
15 for v := range m {
16 x := sets.find(v)
17 m[x] = append(m[x], v)
18 }
19
20 components := make([][]int, 0, count)
21 for _, comp := range m {
22 if comp != nil {
23 components = append(components, comp)
24 }
25 }
26 return components
27 }
28
29 func components(g Iterator) (sets disjointSets, count int) {
30 n := g.Order()
31 sets, count = makeSingletons(n), n
32 for v := 0; v < n && count > 1; v++ {
33 g.Visit(v, func(w int, _ int64) (skip bool) {
34 x, y := sets.find(v), sets.find(w)
35 if x != y {
36 sets.union(x, y)
37 count--
38 if count == 1 {
39 skip = true
40 }
41 }
42 return
43 })
44 }
45 return
46 }
47
48 // Union-find with path compression performs any sequence of m ≥ n find
49 // and n – 1 union operations in O(m log n) time. Union by rank doesn't
50 // seem to improve performance here.
51 type disjointSets []int
52
53 func makeSingletons(n int) disjointSets {
54 p := make(disjointSets, n)
55 for v := range p {
56 p[v] = v
57 }
58 return p
59 }
60
61 func (p disjointSets) find(x int) int {
62 root := x
63 for root != p[root] {
64 root = p[root]
65 }
66 for p[x] != root {
67 p[x], x = root, p[x]
68 }
69 return root
70 }
71
72 func (p disjointSets) union(x, y int) {
73 x, y = p.find(x), p.find(y)
74 if x != y {
75 p[y] = x
76 }
77 }