Function to find number of strongly connected components in the graph.
| 33 | |
| 34 | //Function to find number of strongly connected components in the graph. |
| 35 | int kosaraju(int V, vector<int> adj[]) |
| 36 | { |
| 37 | int i,j; |
| 38 | |
| 39 | stack<int> stk; |
| 40 | |
| 41 | vector<int> result; |
| 42 | vector<bool> visited(V,false); |
| 43 | |
| 44 | for(i=0;i<V;i++) |
| 45 | { |
| 46 | if(!visited[i]) |
| 47 | { |
| 48 | dfs(i,adj,visited,stk); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | while(!stk.empty()) |
| 53 | { |
| 54 | result.push_back(stk.top()); |
| 55 | stk.pop(); |
| 56 | } |
| 57 | |
| 58 | vector<int> g[V]; |
| 59 | |
| 60 | for(i=0;i<V;i++) |
| 61 | { |
| 62 | for(auto x: adj[i]) |
| 63 | { |
| 64 | g[x].push_back(i); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | for(i=0;i<V;i++) visited[i]=false; |
| 69 | |
| 70 | int cnt=0; |
| 71 | |
| 72 | for(i=0;i<V;i++) |
| 73 | { |
| 74 | int node=result[i]; |
| 75 | if(!visited[node]) |
| 76 | { |
| 77 | cnt++; |
| 78 | dfsRec(node,g,visited); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | return cnt; |
| 83 | } |