并查集模版
class UnionFind {
int[] roots;
int size;
public UnionFind(int n) {
this.roots = new int[n];
this.size = n;
for (int i = 0; i < n; i++) {
roots[i] = i;
}
}
public int find(int i) {
if (i == roots[i]) {
return i;
}
return roots[i] = find(roots[i]);
}
public void union(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot != qRoot) {
roots[pRoot] = qRoot;
size--;
}
}
public boolean isConnected(int x, int y) {
return find(x) == find(y);
}
}
参考
- 并查集(Union-Find)算法介绍
- 并查集
- https://blog.csdn.net/wmy0217_/article/details/104972191