并查集
并查集
class UnionFind{
private int[] parents;
UnionFind(int size){
parents = new int[size];
for(int i=0;i < size ;i++) parents[i] = i;
}
public int find(int x){
return x==parents[x]?x:find(parents[x]);
}
public void union(int x,int y){
int xp = find(x);
int yp = find(y);
if(xp == yp) return;
parents[xp] = yp;
}
public boolean isConnect(int x,int y){
return find(x) == find(y);
}
}
Saying Less Doing More