• 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程序:

  • 相关阅读:
    C#发邮件
    C#循环遍历mysql
    【转】C#获取当前日期时间(转)
    C#设置DataGridView控件的标题行的高度并且居中显示
    c#窗体实现验证码
    Git 常用命令清单,掌握这些,轻松驾驭版本管理
    Vue 常见面试问题,你可能都知道,但能答好吗?
    Node 爬虫,批量爬取头条视频并保存
    Node 爬虫,批量下载并保存图片
    NodeJS MySql 执行多条sql语句
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4875755.html
Copyright © 2020-2023  润新知