package Union_Find;
public class MakeConnected_1319 {
// 1319. Number of Operations to Make Network Connected
int[] P;
// 剩余的线
int count;
public int makeConnected(int n, int[][] connections) {
P=new int[n];
count=connections.length;
// 初始化
for(int i=0;i<n;i++) {
P[i]=i;
}
for(int i=0;i<connections.length;i++) {
union(connections[i][0],connections[i][1]);
}
if(count<n-(connections.length-count+1)) {
// 如果剩余的线小于剩余的电脑数
return -1;
}else {
return count;
}
}
private int find(int x) {
return P[x] == x ? x : (P[x] = find(P[x])); //路径压缩
}
private void union(int x,int y) {
int xRoot=find(x);
int yRoot=find(y);
if(xRoot!=yRoot) {
P[xRoot]=yRoot;
count--;
}
}
}
1319. Number of Operations to Make Network Connected(并查集)
最新推荐文章于 2021-06-04 00:38:49 发布