import java.util.Arrays;
public class ConnectIsland {
public int solution(int n, int[][] costs) {
int answer = 0, connection[] = new int[n];
for (int i = 0; i < n; i++) {
connection[i] = i;
}
Arrays.sort(costs, (o1, o2) -> o1[2] - o2[2]);
for (int[] cost : costs) {
if (find(connection, cost[0], cost[1])) {
answer += cost[2];
union(connection, cost[0], cost[1]);
}
}
return answer;
}
private int get(int[] connection, int x) {
if (connection[x] == x)
return x;
return get(connection, connection[x]);
}
private void union(int[] connection, int a, int b) {
a = get(connection, a);
b = get(connection, b);
if (a > b) {
connection[a] = b;
} else {
connection[b] = a;
}
}
private boolean find(int[] connection, int a, int b) {
a = get(connection, a);
b = get(connection, b);
return a == b ? false : true;
}
}