找出有向图中的弱联通分量

请找出有向图中弱联通分量的数目。图中的每个节点包含其邻居的 1 个标签和1 个列表。 (一个有向图中的相连节点指的是一个包含 2 个通过直接边沿路径相连的顶点的子图。)

您在真实的面试中是否遇到过这个题?  
Yes
样例

给定图:

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

返回 {A,B,D}, {C,E,F}. 图中有 2 个相连要素,即{A,B,D} 和 {C,E,F}

挑战

将原素升序排列。

解法:

采用并查集

import java.util.Map.Entry;

/**
 * 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
     */
    public List<List<Integer>> connectedSet2(ArrayList<DirectedGraphNode> nodes)
    {
        Map<Integer, Integer> father = new HashMap<Integer, Integer>();
        for(DirectedGraphNode curNode : nodes) {
            for(DirectedGraphNode curNNode : curNode.neighbors) {
                int curP = find(father, curNode.label);
                int curNP = find(father, curNNode.label);
                if(curP != curNP) {
                    if(curP > curNP) {
                        father.put(curP, curNP);
                    }
                    else {
                        father.put(curNP, curP);
                    }
                }
            }
        }
        Map<Integer, List<Integer>> tMap = new HashMap<Integer, List<Integer>>();
        for(DirectedGraphNode curNode : nodes) {
            int curF = find(father, curNode.label);
            if(!tMap.containsKey(curF)) {
                List<Integer> tmpList = new ArrayList<Integer>();
                tmpList.add(curNode.label);
                tMap.put(curF, tmpList);
            }
            else {
                tMap.get(curF).add(curNode.label);
            }
        }
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        Set<Entry<Integer, List<Integer>>> entrySet = tMap.entrySet();
        for(Entry<Integer, List<Integer>> curEntry : entrySet) {
            ans.add(curEntry.getValue());
        }
        return ans;
    }
    
    private int find(Map<Integer, Integer> father, int cur) {
        if(!father.containsKey(cur)) {
            father.put(cur, cur);
            return cur;
        }
        while(father.get(cur) != cur) {
            cur = father.get(cur);
        }
        return cur;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值