美文网首页
神奇的UnionFind (1)

神奇的UnionFind (1)

作者: 阿沉刷题中 | 来源:发表于2017-09-17 11:21 被阅读0次

今天学习了神奇的并查集,UnionFind,试着做了几道之前用BFS/DFS的算法题,感觉超好用!

UnionFind的基础运用:

  • 创建一个UnionFind
  • 查找某元素所在group的大哥
  • 连接两个元素
  • 判断两个元素是否在同一个group中

那我们来看看题目吧!
Connecting Graph

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), add an edge to connect node a and node b.
    2.query(a, b), check if two nodes are connected
public class ConnectingGraph { 
    private int[] father = null;
    
    private int find(int x) {
        if (father[x] == x) {
            return x;
        }
        return father[x] = find(father[x]);
    }

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

    public void connect(int a, int b) {
        // Write your code here
        int rootA = find(a);
        int rootB = find(b);
        if (rootA != rootB) {
            father[rootA] = rootB;
        }
    }
        
    public boolean  query(int a, int b) {
        // Write your code here
        int rootA = find(a);
        int rootB = find(b);
        return (rootA == rootB);
    }
}

相关文章

  • 神奇的UnionFind (1)

    今天学习了神奇的并查集,UnionFind,试着做了几道之前用BFS/DFS的算法题,感觉超好用! UnionFi...

  • nodejs 并查集

    function UnionFind(row, col, idx){ var o = new Object(); ...

  • UnionFind count islands

    Question quoted from lintcode Given a n,m which means the...

  • 并查集UnionFind

    并查集(UnionFind)主要是用来解决图论中「动态连通性」问题的,数据结构很简单,却能用来表示无向图。简单的代...

  • 并查集 - UnionFind

    基本概念 并查集能高效的查找两个元素是否在一个集合,而且能高效的合并两个集合。 使用树结构(Tree)来表示集合元...

  • 数据结构(六)UnionFind

    之前面试蘑菇街GG了,竟然是因为不懂UnionFind,来总结一下下啦。 用BFS也是可以的啦~

  • LeetCode并查集(UnionFind)小结

    一,概述 并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets UnionFind)的...

  • 并查集(UnionFind)技巧总结

    什么是并查集 在计算机科学中,并查集是一种树型的数据结构,用于处理一些不交集(Disjoint Sets)的合并及...

  • 神奇的结构1

    第一章 作者认为人的感官会给人意识中描述和记录一个对应现实世界的地图。 这个地图受限于人类五感感受能力的限制和差异...

  • 《神奇的佛1》

    轿车停在超市旁,迪坐在里面,两手握着方向盘,她在等着自己的三个孩子。 迪有三个宝贝,都在一所全日制寄宿学...

网友评论

      本文标题:神奇的UnionFind (1)

      本文链接:https://www.haomeiwen.com/subject/sbppsxtx.html