[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 };