最小生成树,按照权重把边排好序,然后从小到大的构建。实时的判断是否出现环的情况,如果不存在,就把这个边加进去(用到了并查集里面的find函数)。
public class test {
public int[] parent;
public int minimunCost(int N, int[][] num){
if(num.length < N-1){
return -1;
}
Arrays.sort(num, new Comparator<int[]>(){
@Override
public int compare(int[] o1, int[] o2) {
return o1[2] - o2[2];
}
});
for(int i=0; i<N; i++){
parent[i] = i;
}
int res = 0;
int bian = 0;
int index = 0;
while(bian < N-1){
int source = num[index][0];
int target = num[index][1];
int weight = num[index][2];
index++;
int x1 = find(source);
int y1 = find(target);
if(x1 != y1){
bian++;
res += weight;
parent[x1] = y1;
}
}
return res;
}
public int find(int x){
if(x != parent[x]){
parent[x] = find(parent[x]);
}
return parent[x];
}
}