-
Notifications
You must be signed in to change notification settings - Fork 10
/
prim.go
91 lines (74 loc) · 1.63 KB
/
prim.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package graphs
import (
"container/heap"
"math"
)
type primNode[T Vertex] struct {
vertex T
cost float64
index int // Index of the node in the heap
visited bool
predecessor *primNode[T]
}
type primPQ[T Vertex] []*primNode[T]
func (pq primPQ[T]) Len() int {
return len(pq)
}
func (pq primPQ[T]) Less(i, j int) bool {
return pq[i].cost < pq[j].cost
}
func (pq primPQ[T]) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index, pq[j].index = i, j
}
func (pq *primPQ[T]) Push(x interface{}) {
n := x.(*primNode[T])
n.index = len(*pq)
*pq = append(*pq, n)
}
func (pq *primPQ[T]) Pop() interface{} {
n := len(*pq)
node := (*pq)[n-1]
*pq = (*pq)[0 : n-1]
return node
}
// Prim implements Prim’s algorithm. It returns a minimal spanning
// tree for the given graph, starting with vertex start.
func Prim[T Vertex](g *Graph[T], start T) *Graph[T] {
tree := NewGraph[T]()
nodes := map[T]*primNode[T]{}
pq := primPQ[T]{}
heap.Init(&pq)
g.EachVertex(func(v T, _ func()) {
n := &primNode[T]{
vertex: v,
cost: math.Inf(1),
visited: false,
}
heap.Push(&pq, n)
nodes[v] = n
})
nodes[start].cost = 0
heap.Fix(&pq, nodes[start].index)
for pq.Len() > 0 {
v := heap.Pop(&pq).(*primNode[T])
v.visited = true
g.EachHalfedge(v.vertex, func(he Halfedge[T], _ func()) {
node := nodes[he.End]
if node.visited {
return
}
if he.Cost < node.cost {
node.cost = he.Cost
node.predecessor = v
heap.Fix(&pq, node.index)
}
})
}
for _, node := range nodes {
if node.predecessor != nil {
tree.AddEdge(node.predecessor.vertex, node.vertex, node.cost)
}
}
return tree
}