给一个图中的
n
个节点, 记为1
到n
. 在开始的时候图中没有边.
你需要完成下面两个方法:
-
connect(a, b)
, 添加一条连接节点 a, b的边 -
query()
, 返回图中联通区域个数
样例
5 // n = 5
query() 返回 5
connect(1, 2)
query() 返回 4
connect(2, 4)
query() 返回 3
connect(1, 4)
query() 返回 3
思路
589. 连接图的follow up,定义count变量来统计连通块个数,初始时各个结点不相连,count大小即为结点个数,只有当结点合并时 count 数目才会减小
代码
public class ConnectingGraph3 {
private int[] father = null;
private int count;
private int find(int x) {
if (father[x] == x) {
return x;
}
return father[x] = find(father[x]);
}
public ConnectingGraph3(int n) {
// initialize your data structure here.
father = new int[n + 1];
count = n;
for (int i = 1; i <= n; ++i) {
father[i] = i;
}
}
public void connect(int a, int b) {
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b) {
father[root_a] = root_b;
count --;
}
}
public int query() {
return count;
}
}