Sunday, April 16, 2017

Find the Weak Connected Component in the Directed Graph

有一点点问题
因为在father里面用的是label代替每一个node所以默认每个label是unique的

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     ArrayList<DirectedGraphNode> neighbors;
 *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 * };
 */
public class Solution {
    /**
     * @param nodes a array of Directed graph node
     * @return a connected set of a directed graph
     */
    private Map<Integer, Integer> father;
    public List<List<Integer>> connectedSet2(ArrayList<DirectedGraphNode> nodes) {
        // Write your code here
        List<List<Integer>> result = new ArrayList<>();
        if (nodes == null || nodes.size() == 0) return result;
        father = new HashMap<>();
        //Initialize every node's father to itself
        for (DirectedGraphNode node : nodes) {
            father.put(node.label, node.label);
        }
     
        for (DirectedGraphNode node : nodes) {
            for (DirectedGraphNode neighbor : node.neighbors) {
                union(node.label, neighbor.label);
            }
        }
        //Result HashMap<key = root node label, value = List<Integer> nodes>
        Map<Integer, List<Integer>> hash = new HashMap<>();
        for (Integer curr : father.keySet()) {
            int root = find(curr);
            if (!hash.containsKey(root)) hash.put(root, new ArrayList<Integer>());
            List<Integer> childrenList = hash.get(root);
            childrenList.add(curr);
        }
        for (List<Integer> list : hash.values()) {
            Collections.sort(list);
            result.add(list);
        }
        return result;
    }
    private int find(int x) {
        if (father.get(x) == x) return x;
        father.put(x, find(father.get(x)));
        return father.get(x);
    }
    private void union(int a, int b) {
        int rootA = find(a);
        int rootB = find(b);
        if (rootA != rootB) {
            father.put(rootA, rootB);
        }
    }
}

No comments:

Post a Comment