LintCode 431 Connected Component in Undirected Graph

来源:互联网 发布:腾讯红包大数据,归属地 编辑:程序博客网 时间:2024/06/07 14:21

Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its neighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.)

简单来说就是找到无向图里的链接块,返回集合。

这里用并查集解决。

public class Solution {    class UnionFind {        HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();        UnionFind(HashSet<Integer> hashSet)        {            for (Integer now : hashSet) {                father.put(now, now);            }        }        int find(int x)        {            int parent = father.get(x);            while (parent != father.get(parent)) {                parent = father.get(parent);            }            return parent;        }        void union(int x, int y)        {            int fa_x = find(x);            int fa_y = find(y);            if (fa_x != fa_y)                father.put(fa_x, fa_y);        }    }    List<List<Integer> > print(HashSet<Integer> hashSet, UnionFind uf, int n) {        List<List<Integer> > ans = new ArrayList<List<Integer> >();         HashMap<Integer, List<Integer> > hashMap = new HashMap<Integer, List<Integer> >();        for (int i : hashSet) {            int fa = uf.find(i);            if (!hashMap.containsKey(fa)) {                hashMap.put(fa, new ArrayList<Integer>());            }            List<Integer> now = hashMap.get(fa);            now.add(i);            hashMap.put(fa, now);        }    //遍历hashmap中的集合们        for (List<Integer> now : hashMap.values()) {            Collections.sort(now);             ans.add(now);        }        return ans;    }public List<List<Integer> > connectedSet(ArrayList<UndirectedGraphNode> nodes)    {        HashSet<Integer> hashSet = new HashSet<Integer>(); //建立hashset存出现的node字符        //循环把无向图里的字符元素都存入hashset中        for (UndirectedGraphNode now : nodes) {            hashSet.add(now.label);            for (UndirectedGraphNode neighbour : now.neighbors) {                hashSet.add(neighbour.label);            }        }        //用并查集构建无线连接图结果        UnionFind uf = new UnionFind(hashSet);        for (UndirectedGraphNode now : nodes) {            for (UndirectedGraphNode neighbour : now.neighbors) {                int fnow = uf.find(now.label);                int fneighbour = uf.find(neighbour.label);                if (fnow != fneighbour) {                    uf.union(now.label, neighbour.label);                }            }        }        //结构建立好了,利用hashmap返回链接块集合,key保存father,value保存father下的节点,即联通块的节点集合        return print(hashSet, uf, nodes.size());    }}
阅读全文
0 0
原创粉丝点击