-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 185.java
More file actions
43 lines (32 loc) · 1.01 KB
/
Day 185.java
File metadata and controls
43 lines (32 loc) · 1.01 KB
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
class Solution {
public int minCost(int[][] houses) {
int n = houses.length;
boolean[] visited = new boolean[n];
int[] minDist = new int[n];
for (int i = 0; i < n; i++) {
minDist[i] = 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(houses[u][0] - houses[v][0]) +
Math.abs(houses[u][1] - houses[v][1]);
if (dist < minDist[v]) {
minDist[v] = dist;
}
}
}
}
return totalCost;
}
}