-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMin Cost to Connect All Points.java
45 lines (41 loc) · 1.49 KB
/
Min Cost to Connect All Points.java
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
// Runtime: 15 ms (Top 99.32%) | Memory: 42.90 MB (Top 99.2%)
class Solution {
public int minCostConnectPoints(int[][] points) {
int len = points.length;
// array that keep track of the shortest distance from mst to each node
int[] disArr = new int[len];
for (int i = 1; i < len; ++i) {
disArr[i] = Integer.MAX_VALUE;
}
// visited[node] == true if node in mst
boolean[] visited = new boolean[len];
visited[0] = true;
int numEdge = 0;
// current node, used to update the disArr
int cur = 0;
// result
int res = 0;
while (numEdge++ < len - 1) {
int minEdge = Integer.MAX_VALUE;
int next = -1;
for (int i = 0; i < len; ++i) {
// if the node i is not in mst
if (!visited[i]) {
// find the distance between cur and i
int dis = Math.abs(points[cur][0] - points[i][0]) + Math.abs(points[cur][1] - points[i][1]);
// update distance array
disArr[i] = Math.min(dis, disArr[i]);
// find the shortest edge
if (disArr[i] < minEdge) {
minEdge = disArr[i];
next = i;
}
}
}
cur = next;
visited[cur] = true;
res += minEdge;
}
return res;
}
}