zoukankan      html  css  js  c++  java
  • [LintCode] Find the Weak Connected Component in the Directed Graph

    Find the Weak Connected Component in the Directed Graph

    Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a connected set of a directed graph is a subgraph in which any two vertices are connected by direct edge path.)

    Example

    Given graph:

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

    Return {A,B,D}, {C,E,F}. Since there are two connected component which are{A,B,D} and {C,E,F}

    Note

    Sort the element in the set in increasing order

    Union-Find,并查集!注意fa每次都要重新求,因为fa的值可能在之前的循环中被更新。

     1 /**
     2  * Definition for Directed graph.
     3  * struct DirectedGraphNode {
     4  *     int label;
     5  *     vector<DirectedGraphNode *> neighbors;
     6  *     DirectedGraphNode(int x) : label(x) {};
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     /**
    12      * @param nodes a array of directed graph node
    13      * @return a connected set of a directed graph
    14      */
    15     int find(unordered_map<int, int> &father, int x) {
    16         if (father.find(x) == father.end()) {
    17             father[x] = x;
    18             return x;
    19         }
    20         while (x != father[x]) x = father[x];
    21         return x;
    22     }
    23     vector<vector<int>> connectedSet2(vector<DirectedGraphNode*>& nodes) {
    24         // Write your code here
    25         unordered_map<int, int> father;
    26         int fa, fb, fn;
    27         for (auto &n : nodes) {
    28             for (auto &nn : n->neighbors) {
    29                 fa = find(father, n->label);
    30                 fb = find(father, nn->label);
    31                 if (fa != fb) {
    32                     if (fa > fb) father[fa] = fb;
    33                     else father[fb] = fa;
    34                 }
    35             }
    36         }
    37         unordered_map<int, vector<int>> comp;
    38         for (auto &n : nodes) {
    39             fn = find(father, n->label);
    40             comp[fn].push_back(n->label);
    41         }
    42         vector<vector<int>> res;
    43         for (auto &c : comp) {
    44             sort(c.second.begin(), c.second.end());
    45             res.push_back(c.second);
    46         }
    47         return res;
    48     }
    49 };
  • 相关阅读:
    我们工作到底为了什么
    阿里云是如何做好高并发的
    织梦cms PHPcms 帝国cms比较
    正确修改MySQL最大连接数的三种好用方案
    微信开发的几个小功能
    命令行下运行php的方法和技巧
    PHP去除连续空格
    ajax,django
    web框架,HTTP协议
    Django 模型Model层2
  • 原文地址:https://www.cnblogs.com/easonliu/p/4607300.html
Copyright © 2011-2022 走看看