Repository navigation
Expand file tree
/
Copy pathcomponents.go
More file actions
259 lines (225 loc) · 6.87 KB
/
Copy pathcomponents.go
File metadata and controls
259 lines (225 loc) · 6.87 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package gograph
// ConnectedComponents returns the connected components of g. For a directed
// graph, edge directions are ignored, so it returns the weakly connected
// components. The vertices in the result are the vertices stored in g, not
// copies, and an empty graph returns an empty slice.
//
// The components are in the order of their first vertex in GetAllVertices.
// In an undirected graph, the vertices of a component are in breadth-first
// order from that vertex, following the order the edges were added. In a
// directed graph, they are in GetAllVertices order. The components share one
// backing array, but appending to one doesn't change the others.
//
// A graph from New is read from the neighbor lists stored on its vertices.
// An undirected one takes O(V+E) time. A directed one takes O((V+E)·α(V))
// time, where α is the inverse Ackermann function, which is below 5 for any
// graph that fits in memory. Both use O(V) extra space. Other directed Graph
// implementations are read through GetAllVertices and AllEdges, also in
// O((V+E)·α(V)) time. Other undirected Graph implementations are read through
// GetAllVertices and EdgesOf, with one EdgesOf call per vertex. It panics if
// g is nil.
//
// connectivity.ConnectedComponents calls this.
func ConnectedComponents[T comparable](g Graph[T]) [][]*Vertex[T] {
bg, ok := g.(*baseGraph[T])
if g == nil || (ok && bg == nil) {
panic("gograph: ConnectedComponents requires a non-nil graph")
}
if ok {
if bg.properties.isDirected {
return bg.weakComponents()
}
return bg.components()
}
return componentsByEdges(g)
}
// componentsByEdges searches through EdgesOf, calling it once per vertex.
func componentsByEdges[T comparable](g Graph[T]) [][]*Vertex[T] {
if g.IsDirected() {
return directedComponentsByEdges(g)
}
visited := make(map[*Vertex[T]]bool)
components := make([][]*Vertex[T], 0)
for _, root := range g.GetAllVertices() {
if visited[root] {
continue
}
visited[root] = true
queue := []*Vertex[T]{root}
component := make([]*Vertex[T], 0)
for len(queue) > 0 {
vertex := queue[0]
queue = queue[1:]
component = append(component, vertex)
for _, edge := range g.EdgesOf(vertex) {
neighbor := edge.OtherVertex(vertex.Label())
if neighbor == nil || visited[neighbor] {
continue
}
visited[neighbor] = true
queue = append(queue, neighbor)
}
}
components = append(components, component)
}
return components
}
// directedComponentsByEdges joins the endpoints of every edge, ignoring its
// direction, then groups vertices in GetAllVertices order.
func directedComponentsByEdges[T comparable](g Graph[T]) [][]*Vertex[T] {
vertices := g.GetAllVertices()
indices := make(map[T]int, len(vertices))
parent := make([]int, len(vertices))
for i, vertex := range vertices {
indices[vertex.Label()] = i
parent[i] = -1
}
for _, edge := range g.AllEdges() {
if edge == nil || edge.Source() == nil || edge.Destination() == nil {
continue
}
from, fromOK := indices[edge.Source().Label()]
to, toOK := indices[edge.Destination().Label()]
if !fromOK || !toOK {
continue
}
a, b := findRoot(parent, from), findRoot(parent, to)
if a == b {
continue
}
// Attach the smaller set to the larger one.
if parent[a] > parent[b] {
a, b = b, a
}
parent[a] += parent[b]
parent[b] = a
}
count := 0
for _, p := range parent {
if p < 0 {
count++
}
}
// index is one more than the component of each root, or 0 until the
// first vertex of the set is placed.
index := make([]int, len(vertices))
members := make([]*Vertex[T], len(vertices))
components := make([][]*Vertex[T], 0, count)
next := 0
for i, vertex := range vertices {
root := findRoot(parent, i)
if index[root] == 0 {
size := -parent[root]
components = append(components, members[next:next:next+size])
next += size
index[root] = len(components)
}
c := index[root] - 1
components[c] = append(components[c], vertex)
}
return components
}
// components runs a breadth-first search over the neighbor lists stored on
// the vertices. An undirected graph stores each edge in both directions, so
// the neighbor list of a vertex has every vertex it shares an edge with.
func (g *baseGraph[T]) components() [][]*Vertex[T] {
// comp is the component of each vertex, by position, or -1 until the
// search reaches it.
comp := make([]int, len(g.order))
for i := range comp {
comp[i] = -1
}
// The search order is the result: each component is a run of the queue.
queue := make([]*Vertex[T], 0, len(g.vertices))
count := 0
for _, root := range g.order {
if root == nil || comp[root.position] >= 0 {
continue
}
comp[root.position] = count
queue = append(queue, root)
for head := len(queue) - 1; head < len(queue); head++ {
for _, neighbor := range queue[head].neighbors {
if comp[neighbor.position] < 0 {
comp[neighbor.position] = count
queue = append(queue, neighbor)
}
}
}
count++
}
components := make([][]*Vertex[T], 0, count)
start := 0
for end := 1; end <= len(queue); end++ {
if end == len(queue) || comp[queue[end].position] != comp[queue[start].position] {
components = append(components, queue[start:end:end])
start = end
}
}
return components
}
// weakComponents joins the two ends of every edge with union-find, so it
// doesn't need a list of the edges that end at each vertex.
func (g *baseGraph[T]) weakComponents() [][]*Vertex[T] {
// parent links each vertex, by position, toward the root of its set. A
// root holds minus the size of its set.
parent := make([]int, len(g.order))
for i := range parent {
parent[i] = -1
}
for _, v := range g.order {
if v == nil {
continue
}
for _, neighbor := range v.neighbors {
a, b := findRoot(parent, v.position), findRoot(parent, neighbor.position)
if a == b {
continue
}
// attach the smaller set to the larger one
if parent[a] > parent[b] {
a, b = b, a
}
parent[a] += parent[b]
parent[b] = a
}
}
count := 0
for i, v := range g.order {
if v != nil && parent[i] < 0 {
count++
}
}
// index is one more than the component of each root, or 0 until the
// first vertex of the set is placed.
index := make([]int, len(g.order))
vertices := make([]*Vertex[T], len(g.vertices))
components := make([][]*Vertex[T], 0, count)
next := 0
for i, v := range g.order {
if v == nil {
continue
}
root := findRoot(parent, i)
if index[root] == 0 {
size := -parent[root]
components = append(components, vertices[next:next:next+size])
next += size
index[root] = len(components)
}
c := index[root] - 1
components[c] = append(components[c], v)
}
return components
}
// findRoot returns the root of the set that x is in, and halves the path
// from x to it.
func findRoot(parent []int, x int) int {
for parent[x] >= 0 {
if grandparent := parent[parent[x]]; grandparent >= 0 {
parent[x] = grandparent
}
x = parent[x]
}
return x
}