591. 连接图 III

描述

给一个图中的n个节点, 记为1n. 在开始的时候图中没有边.
你需要完成下面两个方法:

  1. connect(a, b), 添加一条连接节点 a, b的边
  2. 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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。