-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKosarajuAlgo.cpp
64 lines (55 loc) · 1.41 KB
/
KosarajuAlgo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution
{
private:
void dfs(int node, vector<int>&visited,vector<vector<int>>& adj,stack<int>&st){
visited[node]=1;
for(auto it:adj[node]){
if(!visited[it]){
dfs(it,visited,adj,st);
}
}
st.push(node);
}
//Function to find number of strongly connected components in the graph.
void dfs3(int node,vector<int>&visited,vector<int> adjT[]){
visited[node]=1;
for(auto it:adjT[node]){
if(!visited[it]){
dfs3(it,visited,adjT);
}
}
}
public:
int kosaraju(int V, vector<vector<int>>& adj)
{
//code here
// Step-1 Sort all edges on the basis of finishing time
vector<int>visited(V,0);
stack<int>st;
for(int i=0;i<V;i++){
if(!visited[i]){
dfs(i,visited,adj,st);
}
}
// Step-2 Reverse the Graph
vector<int>adjT[V];
for(int i=0;i<V;i++){
visited[i]=0;
for(auto it:adj[i]){
// i->it;
adjT[it].push_back(i);
}
}
// Step-3 Do DFS
int scc=0;
while(!st.empty()){
int node=st.top();
st.pop();
if(!visited[node]){
scc++;
dfs3(node,visited,adjT);
}
}
return scc;
}
};