Connecting Graph

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), add an edge to connect node a and node b.
2.query(a, b), check if two nodes are connected

Example

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

这题就是实现一个最基础的Union Find. 需要新建一个int[] father来代表每个节点的老板节点。注意这里的find()是路径压缩后的方法,时间复杂度是O(1). 而且connect一定要记住,是connect两个节点的大老板节点。也就是老师说的:“老大哥之间合并,跟小弟没关系”。 同时,query的时候也是查看两个节点的根节点(大老板,老大哥)是不是一样,而跟他们本身没有关系。

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

    public void connect(int a, int b) {
        // Write your code here
        int c = find(a);
        int d = find(b);
        if (c != d){
            father[d] = c;
        }
    }
        
    public boolean query(int a, int b) {
        // Write your code here
        int c = find(a);
        int d = find(b);
        if (c == d){
            return true;
        }
        return false;
    }
    
    private int find(int a){
        if (father[a] == a){
            return a;
        }
        return father[a] = find(father[a]);
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/4020b9229cad
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞