-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin-cost-to-connect-all-points.go
124 lines (102 loc) · 2.42 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"fmt"
"math"
)
// source: https://leetcode.com/problems/min-cost-to-connect-all-points/
const max = math.MaxInt
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
// Optimized Prim's algorithm
func minCostConnectPoints(points [][]int) int {
l := len(points)
visited := make([]bool, l)
dist := make([]int, l)
for i := 0; i < l; i++ {
dist[i] = max
}
var v, res, minDist int
dist[v] = 0
for minDist != max {
visited[v] = true
res += dist[v]
for i := 0; i < l; i++ {
if i == v || visited[i] {
continue
}
if d := abs(points[v][0]-points[i][0]) + abs(points[v][1]-points[i][1]); d < dist[i] {
dist[i] = d
}
}
minDist = max
for i := 0; i < l; i++ {
if !visited[i] && (dist[i] < minDist) {
minDist, v = dist[i], i
}
}
}
return res
}
// First, for given set of points build a graph, then
// use Prim's algorithm to form min spanning tree
// return sum of edges in this tree
func minCostConnectPoints_(points [][]int) (res int) {
l := len(points)
if l == 1 {
return 0
}
var verCnt, ver, min int
var visited = make([]bool, l)
edges := make([][]int, l)
for i := 0; i < l; i++ {
edges[i] = make([]int, l)
for j := 0; j < l; j++ {
if i == j {
edges[i][j] = max
}
edges[i][j] = abs(points[i][0]-points[j][0]) + abs(points[i][1]-points[j][1])
}
}
visited[0] = true
for verCnt < l-1 {
min = max
for i := 0; i < l; i++ {
if visited[i] {
for j := 0; j < l; j++ {
if !visited[j] && edges[i][j] < min {
min = edges[i][j]
ver = j
}
}
}
}
res += min
visited[ver] = true
verCnt++
}
return res
}
func main() {
// Example 5
var points5 = [][]int{{2, -3}, {-17, -8}, {13, 8}, {-17, -15}}
fmt.Println("Expected: 53 Output: ", minCostConnectPoints(points5))
// Example 6
var points6 = [][]int{{0, 0}, {1, 1}, {1, 0}, {-1, 1}}
fmt.Println("Expected: 4 Output: ", minCostConnectPoints(points6))
// Example 1
var points1 = [][]int{{0, 0}, {2, 2}, {3, 10}, {5, 2}, {7, 0}}
fmt.Println("Expected: 20 Output: ", minCostConnectPoints(points1))
// Example 2
var points2 = [][]int{{3, 12}, {-2, 5}, {-4, 1}}
fmt.Println("Expected: 18 Output: ", minCostConnectPoints(points2))
// Example 3
var points3 = [][]int{{3, 13}}
fmt.Println("Expected: 0 Output: ", minCostConnectPoints(points3))
// Example 4
var points4 = [][]int{{0, 0}, {1, 1}}
fmt.Println("Expected: 2 Output: ", minCostConnectPoints(points4))
}