-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmin_cost_to_connect_all_points.go
79 lines (62 loc) · 1.41 KB
/
min_cost_to_connect_all_points.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
package main
import (
"container/heap"
"math"
)
type Pair struct {
node int
distance int
}
type PairHeap []Pair
func (h PairHeap) Len() int { return len(h) }
func (h PairHeap) Less(i, j int) bool { return h[i].distance < h[j].distance }
func (h PairHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *PairHeap) Push(x interface{}) {
*h = append(*h, x.(Pair))
}
func (h *PairHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func minCostConnectPoints(points [][]int) int {
n := len(points)
adjList := make([][]Pair, n)
for i := 0; i < n; i++ {
adjList[i] = make([]Pair, 0)
}
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
first := points[i]
second := points[j]
weight := int(math.Abs(float64(first[0]-second[0])) + math.Abs(float64(first[1]-second[1])))
adjList[i] = append(adjList[i], Pair{j, weight})
adjList[j] = append(adjList[j], Pair{i, weight})
}
}
visited := make([]bool, n)
pq := make(PairHeap, 0)
heap.Init(&pq)
pq = append(pq, Pair{0, 0})
sum := 0
for len(pq) > 0 {
pair := heap.Pop(&pq).(Pair)
node := pair.node
dist := pair.distance
if visited[node] {
continue
}
visited[node] = true
sum += dist
for _, adj := range adjList[node] {
adjNode := adj.node
adjDistance := adj.distance
if !visited[adjNode] {
heap.Push(&pq, Pair{adjNode, adjDistance})
}
}
}
return sum
}