1
+ func minCostConnectPoints (points [][]int ) int {
2
+
3
+ n := len (points )
4
+ adj := make ([][][]int , n )
5
+ for i := 0 ; i < n ; i ++ {
6
+ x1 , y1 := points [i ][0 ], points [i ][1 ]
7
+ for j := i + 1 ; j < n ; j ++ {
8
+ x2 , y2 := points [j ][0 ], points [j ][1 ]
9
+ dist := abs (x1 - x2 ) + abs (y1 - y2 )
10
+ adj [i ] = append (adj [i ], []int {dist , j })
11
+ adj [j ] = append (adj [j ], []int {dist , i })
12
+ }
13
+ }
14
+ // prims
15
+ res := 0
16
+ visited := make (map [int ]bool )
17
+
18
+ h := & IntHeap {[2 ]int {0 , 0 }}
19
+
20
+ for len (visited ) < n {
21
+ pntObj := heap .Pop (h ).([2 ]int )
22
+ cost , pnt := pntObj [0 ], pntObj [1 ]
23
+
24
+ if visited [pnt ] {
25
+ continue
26
+ }
27
+ res += cost
28
+ visited [pnt ] = true
29
+
30
+ for _ , neighbour := range adj [pnt ] {
31
+ nCost , nPoint := neighbour [0 ], neighbour [1 ]
32
+
33
+ if ! visited [nPoint ] {
34
+ heap .Push (h , [2 ]int {nCost , nPoint })
35
+ }
36
+ }
37
+ }
38
+ return res
39
+ }
40
+
41
+ func abs (n int ) int {
42
+ if n > 0 {
43
+ return n
44
+ }
45
+ return - n
46
+ }
47
+
48
+ type IntHeap [][2 ]int
49
+
50
+ func (h IntHeap ) Len () int { return len (h ) }
51
+ func (h IntHeap ) Less (i , j int ) bool { return h [i ][0 ] < h [j ][0 ] }
52
+ func (h IntHeap ) Swap (i , j int ) { h [i ], h [j ] = h [j ], h [i ] }
53
+
54
+ func (h * IntHeap ) Push (x interface {}) {
55
+ * h = append (* h , x .([2 ]int ))
56
+ }
57
+
58
+ func (h * IntHeap ) Pop () interface {} {
59
+ old := * h
60
+ n := len (old )
61
+ x := old [n - 1 ]
62
+ * h = old [:n - 1 ]
63
+ return x
64
+ }
0 commit comments