码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode 容易题:Find the Connected Component in the Undirected Graph 找出无向图汇总的相连要素

时间:2015-10-13 21:06:13      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

题目:

请找出无向图中相连要素的个数。

图中的每个节点包含其邻居的 1 个标签和 1 个列表。(一个无向图的相连节点(或节点)是一个子图,其中任意两个顶点通过路径相连,且不与超级图中的其它顶点相连。)

样例

给定图:

A------B  C
 \     |  | 
  \    |  |
   \   |  |
    \  |  |
      D   E

返回 {A,B,D}, {C,E}。其中有 2 个相连的元素,即{A,B,D}, {C,E}

解题:

广度优先+递归,写不出来,程序来源

Java程序:

技术分享
/**
 * Definition for Undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
    /**
     * @param nodes a array of Undirected graph node
     * @return a connected set of a Undirected graph
     */
    public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) {
        // Write your code here
        
        int m = nodes.size();
        Map<UndirectedGraphNode, Boolean> visited = new HashMap<>();
        
       for (UndirectedGraphNode node : nodes){
            visited.put(node, false);
       }
        
        List<List<Integer>> result = new ArrayList<>();
        
        for (UndirectedGraphNode node : nodes){
            if (visited.get(node) == false){
                bfs(node, visited, result);
            }
        }
        
        return result;
    }
    
    
    public void bfs(UndirectedGraphNode node, Map<UndirectedGraphNode, Boolean> visited, List<List<Integer>> result){
        
        List<Integer>row = new ArrayList<>();
        
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        visited.put(node, true);
        queue.offer(node);
        
        while (!queue.isEmpty()){
            UndirectedGraphNode u = queue.poll();
            row.add(u.label);
            
            for (UndirectedGraphNode v : u.neighbors){
                if (visited.get(v) == false){
                    visited.put(v, true);
                    queue.offer(v);
                }
            }
        }
        
        Collections.sort(row);
        result.add(row);
        
    }
}
View Code

总耗时: 7732 ms

Python程序:

 

lintcode 容易题:Find the Connected Component in the Undirected Graph 找出无向图汇总的相连要素

标签:

原文地址:http://www.cnblogs.com/theskulls/p/4875755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!