MST
, 크루스칼 알고리즘
https://school.programmers.co.kr/learn/courses/30/lessons/42861
import java.util.*;
class Solution {
static int[] parent;
public int solution(int n, int[][] costs) {
parent = new int[n];
int answer = 0;
for(int i=0; i<n; i++) {
parent[i] = i;
}
Arrays.sort(costs, (o1, o2) -> {
return o1[2] - o2[2];
});
for(int[] cost : costs) {
if(find(cost[0]) != find(cost[1])) {
union(cost[0], cost[1]);
answer += cost[2];
}
}
return answer;
}
public void union(int x, int y) {
x = find(x);
y = find(y);
if(x != y) {
if(x <= y) {
parent[y] = x;
} else {
parent[x] = y;
}
}
}
public int find(int x) {
if(parent[x] == x) {
return x;
}
return parent[x] = find(parent[x]);
}
}
1시간