节点连通问题一般来说有两个思路:
1、化作图论问题,是否连通变为深度/广度优先搜索,连通个数为连通分量
2、构造并查集解决
两者代码复杂度差不多但并查集时间复杂度更低
注意:只适用于无向图的情况
class UnionFind {
private int[] id;
public UnionFind(int N) {
id = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i; //初始化
}
}
void put(int origin, int target) {
//递归到父节点再进行连通合并
while (id[origin] != origin) {
origin = id[origin];
}
while (id[target] != target) {
target = id[target];
}
id[origin] = target;
}
//递归获取并比对父节点
boolean connected(int origin, int target) {
while (id[origin] != origin) {
origin = id[origin];
}
while (id[target] != target) {
target = id[target];
}
return origin == target;
}
//获取父节点数
public int getConnectionNum() {
int r = 0;
for (int i = 0; i < id.length; i++) {
if (id[i] == i) r++;
}
return r;
}
}