Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a connected set of a directed graph is a subgraph in which any two vertices are connected by direct edge path.)

Sort the element in the set in increasing order

Example

Given graph:

A--- > B  C
 \     |  | 
  \    |  |
   \   |  |
    \  v  v
    - >D  E <- F

Return{A,B,D}, {C,E,F}.

    public List<List<Integer>> connectedSet2(ArrayList<DirectedGraphNode> nodes) {
        HashSet<Integer> hashSet = new HashSet<Integer>();

        for(int i = 0; i < nodes.size(); i++){
            hashSet.add(nodes.get(i).label);
            for(DirectedGraphNode neighbour : nodes.get(i).neighbors){
                hashSet.add(neighbour.label);
            }
        }
        UnionFind uf = new UnionFind(hashSet);

        for(DirectedGraphNode node : nodes){
            for(DirectedGraphNode neighbour : node.neighbors){
                uf.union(node.label, neighbour.label);
            }
        }

        return print(hashSet, uf);
    }

    List<List<Integer> > print(HashSet<Integer> hashSet, UnionFind uf) {
        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.compressed_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);
        }
        for (List<Integer> now : hashMap.values()) {
            Collections.sort(now);
            ans.add(now);
        }
        return ans;
    }

    class UnionFind{
            HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();

            public UnionFind(HashSet<Integer> hashSet){
                for(Integer node : hashSet){
                    father.put(node, node);
                }
            }

            public int compressed_find(int x){
                int parent = x;
                while(parent != father.get(parent)){
                    parent = father.get(parent);
                }
                int next;
                while(x != father.get(x)){
                    next = father.get(x);
                    father.put(x, parent);
                    x = next;
                }
                return parent;
            }

            public void union(int x, int y){
                int fa_x = compressed_find(x);
                int fa_y = compressed_find(y);
                if(fa_x != fa_y){
                    father.put(fa_x, fa_y);
                }
            }
    }

results matching ""

    No results matching ""