Connecting Graph III

Given n nodes in a graph labeled from 1 to n. There is no edges in the graph at beginning.

You need to support the following method:

  1. connect(a, b), an edge to connect node a and node b
  2. query(), Returns the number of connected component in the graph

Have you met this question in a real interview? Yes
Example

 5 // n = 5
query() return 5
connect(1, 2)
query() return 4
connect(2, 4)
query() return 3
connect(1, 4)
query() return 3

这道题又比Connecting Graph多了一个求联通块总数,只需要多一个成员变量count来记录. 每次connect的时候总块数减一,query()的时候返回count就行了。

public class ConnectingGraph3 {
    
    public int[] father = null;
    int count;
    public ConnectingGraph3(int n) {
        // initialize your data structure here.
        father = new int[n + 1];
        for (int i = 0; i < n + 1; i++){
            father[i] = i;
        }
        count = n;
    }

    public void connect(int a, int b) {
        // Write your code here
        int root_a = find(a);
        int root_b = find(b);
        if (root_a != root_b){
            father[root_b] = root_a;
            count--;
        }
    }
        
    public int query() {
        // Write your code here
        return count; 
    }
    
    private int find(int a){
        if (father[a] == a){
            return a;
        }
        return father[a] = find(father[a]);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容