-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathkruskal_mst.go
More file actions
43 lines (39 loc) · 744 Bytes
/
kruskal_mst.go
File metadata and controls
43 lines (39 loc) · 744 Bytes
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
package algs4
// KruskalMST ...
type KruskalMST struct {
mst *Queue
weight float32
}
// NewKruskalMST ...
func NewKruskalMST(g *EdgeWeightedGraph) *KruskalMST {
mst := NewQueue()
k := &KruskalMST{mst, 0}
pq := NewMinPQ()
for _, e := range g.Edges() {
pq.Insert(e)
}
uf := NewUF(g.V())
for !pq.IsEmpty() && mst.Size() < g.V()-1 {
e := pq.DelMin().(*Edge)
v := e.Either()
w := e.Other(v)
if uf.Connected(v, w) {
continue
}
uf.Union(v, w)
k.mst.Enqueue(e)
k.weight += e.Weight()
}
return k
}
// Weight ...
func (k *KruskalMST) Weight() float32 {
return k.weight
}
// Edges ...
func (k *KruskalMST) Edges() (edges []*Edge) {
for _, e := range k.mst.Slice() {
edges = append(edges, e.(*Edge))
}
return
}