Connecting Graph II

Given n nodes in a graph labeled from1 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(a), Returns the number of connected component nodes which include node a.

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

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

这道题相对于Connecting Graph I 多出了一个要求a所在联通块的节点个数。这里我们多创建一个int[] size来记录每个节点所在联通块的节点个数。当connect(a,b)的时候,如果root_a != root_b, 我们让root_b认root_a为爸爸,那么root_a所在联通块的size就要加上之前root_b所在联通块的size. 而这道题很容易错的地方其实是query(a), 这里不能直接返回size[a], 二是要返回size[find(a)], size永远按老大哥的来计算,跟小弟无关。

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

    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;
            size[root_a] += size[root_b];
        }
    }
        
    public int query(int a) {
        // Write your code here
        int root_a = find(a);
        return size[root_a];
    }
    
    private int find(int a){
        if (father[a] == a){
            return a;
        }
        return father[a] = find(father[a]);
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/1d3a381a1ee4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞