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 };
  • 相关阅读:
    AChartEngine方法的使用及事件汇总
    免费的Android UI库及组件推荐
    消灭Bug!十款免费移动应用测试框架推荐
    AChartEngine 安卓折线图 柱形图等利器
    添加几个有用的网址
    演示Android百度地图操作功能
    Android 如何在Eclipse中查看Android API源码 及 support包源码
    Android入门之GPS定位详解
    软考之数据库部分
    SSE && WebSockets
  • 原文地址:https://www.cnblogs.com/easonliu/p/4607300.html
Copyright © 2011-2022 走看看