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

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • Given n nodes in a graph labeled from1 to `n. There is no...
    greatseniorsde阅读 223评论 0 0
  • 麦田地里 小溪旁 草垛之上 杨柳树下 你挎着编织框 装满山野菜 那三间瓦房 一只花狗 四米建方的菜园子 飘着饭菜香...
    初之阅读 233评论 0 2
  • 都准备睡了想起来这几日迷恋消消乐玩的忘了要写字这样的事了,不该呀,这样一想就忍住没有睡爬起来了,可是真的这会儿没有...
    物理不好的姑娘最可爱阅读 106评论 0 0
  • 文化旅人余秋雨在出版《借我一生》前接受记者专访时说——我写这本书,决不想与诽谤者辩论,也不想对媒体和读者表白。我只...
    素素_sky阅读 115评论 0 0