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 with which any of the vertices is 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 is and connected component which is{A,B,D} and {C,E,F}
Note
Sort the element in the set in increasing order.
Solution:
and check the set. Iterate through each change and update the collection where each node resides.
/** Definition for Directed graph. * struct DIRECTEDGRAPHNODE {* int label; * Vector<directedgraphnode *&G T Neighbors; * Directedgraphnode (int x): label (x) {}; * }; */classSolution {//Use union-set to solvePrivate: intFind (unordered_map<int,int> &nodemap,intlabel) { if(nodemap.find (label) = =Nodemap.end ()) {Nodemap[label]=label; returnlabel; //If this node doesn ' t belong to any union-set, create a new set}Else{ //This node belongs to some set, find the root of the set intres =Nodemap[label]; while(Nodemap[res]! =Res) Res=Nodemap[res]; returnRes; } } Public: /** * @param nodes A array of directed graph node * @return A connected set of a directed graph*/Vector<vector<int>> ConnectedSet2 (vector<directedgraphnode*>&nodes) {Unordered_map<int,int>Nodemap; Vector<vector<int> >result; for(inti =0; i < nodes.size (); + +i) { for(intj =0; J < (nodes[i]->neighbors). Size (); + +j) { intS1 = Find (Nodemap, nodes[i]->label); intS2 = Find (Nodemap, (nodes[i]->neighbors) [j]->label); if(S1! =S2) { //Union sets if(S1 < s2) NODEMAP[S2] =S1; ElseNODEMAP[S1] =S2; }Else{ // do nothing} }} unordered_map<int,int>Setid2vecid; for(inti =0; i < nodes.size (); + +i) { intLabel = nodes[i]->label; intSetId =Find (nodemap, label); if(Setid2vecid.find (setId) = =Setid2vecid.end ()) {Vector<int>VEC; Setid2vecid[setid]=result.size (); Result.push_back (VEC); } intIDX =Setid2vecid[setid]; Result[idx].push_back (label); } for(inti =0; i < result.size (); + +i) sort (Result[i].begin (), Result[i].end ()); returnresult; }};
Inspired by:http://www.cnblogs.com/easonliu/p/4607300.html
[Lintcode] Find the Weak Connected Component in the Directed Graph