-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminCostConnectPoints.java
More file actions
38 lines (28 loc) · 953 Bytes
/
minCostConnectPoints.java
File metadata and controls
38 lines (28 loc) · 953 Bytes
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
class Solution {
public int minCostConnectPoints(int[][] points) {
int n = points.length;
boolean[] visited = new boolean[n];
int[] minDist = new int[n];
Arrays.fill(minDist, Integer.MAX_VALUE);
minDist[0] = 0;
int totalCost = 0;
for (int i = 0; i < n; i++) {
int u = -1;
for (int j = 0; j < n; j++) {
if (!visited[j] && (u == -1 || minDist[j] < minDist[u])) {
u = j;
}
}
visited[u] = true;
totalCost += minDist[u];
for (int v = 0; v < n; v++) {
if (!visited[v]) {
int dist = Math.abs(points[u][0] - points[v][0]) +
Math.abs(points[u][1] - points[v][1]);
minDist[v] = Math.min(minDist[v], dist);
}
}
}
return totalCost;
}
}