-
Notifications
You must be signed in to change notification settings - Fork 23
/
lazy_prim_mst.go
67 lines (59 loc) · 1.1 KB
/
lazy_prim_mst.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package algs4
// LazyPrimMST ...
type LazyPrimMST struct {
marked []bool
mst *Queue
pq *MinPQ
weight float32
}
// NewLazyPrimMST ...
func NewLazyPrimMST(g *EdgeWeightedGraph) *LazyPrimMST {
marked := make([]bool, g.V())
pq := NewMinPQ()
mst := NewQueue()
l := &LazyPrimMST{marked, mst, pq, 0}
for v := 0; v < g.V(); v++ {
if !l.marked[v] {
l.prim(g, v)
}
}
return l
}
func (l *LazyPrimMST) prim(g *EdgeWeightedGraph, v int) {
l.visit(g, v)
for !l.pq.IsEmpty() {
e := l.pq.DelMin().(*Edge)
v := e.Either()
w := e.Other(v)
if l.marked[v] && l.marked[w] {
continue
}
l.mst.Enqueue(e)
l.weight += e.Weight()
if !l.marked[v] {
l.visit(g, v)
}
if !l.marked[w] {
l.visit(g, w)
}
}
}
func (l *LazyPrimMST) visit(g *EdgeWeightedGraph, v int) {
l.marked[v] = true
for _, e := range g.Adj(v) {
if !l.marked[e.Other(v)] {
l.pq.Insert(e)
}
}
}
// Weight ...
func (l *LazyPrimMST) Weight() float32 {
return l.weight
}
// Edges ...
func (l *LazyPrimMST) Edges() (edges []*Edge) {
for _, e := range l.mst.Slice() {
edges = append(edges, e.(*Edge))
}
return
}