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


    题目:

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

    图中的每个节点包含其邻居的 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程序:

  • 相关阅读:
    LeetCode——376.摆动序列
    kaggle——分销商产品未来销售情况预测
    LeetCode——264. 丑数 II
    LeetCode——71.简化路径
    LeetCode——15. 三数之和
    kaggle——NFL Big Data Bowl 2020 Official Starter Notebook
    LeetCode——199. 二叉树的右视图
    数据结构与算法——哈希函数和哈希表等(2)
    数据结构与算法——哈希函数与哈希表等(1)
    Python——Pandas 时间序列数据处理
  • 原文地址:https://www.cnblogs.com/theskulls/p/4875755.html
Copyright © 2020-2023  润新知