-
Notifications
You must be signed in to change notification settings - Fork 105
/
kosaraju_algorithm.cpp
67 lines (64 loc) · 1.33 KB
/
kosaraju_algorithm.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
65
66
67
//Function to find number of strongly connected components in the graph.
// Time complexity O(V+E)
int vis[5001];
int vis2[5001];
void topo(int v,vector<int>adj[],stack<int>&s)
{
vis[v]=1;
for(auto it:adj[v])
{
if(!vis[it])
{
topo(it,adj,s);
}
}
s.push(v);
}
void dfs(int v,vector<int>adj[])
{
vis2[v]=1;
for(auto it:adj[v])
{
if(!vis2[it])
{
dfs(it,adj);
}
}
}
int kosaraju(int V, vector<int> adj[])
{
//code here
memset(vis,0,sizeof(vis));
stack<int>s;
for(int i=0;i<V;i++)
{
if(!vis[i])
{
topo(i,adj,s);
}
}
vector<int>adjT[V];
for(int i=0;i<V;i++)
{
if(adj[i].size()>0)
{
for(auto it:adj[i])
{
adjT[it].push_back(i);
}
}
}
memset(vis2,0,sizeof(vis2));
int ans=0;
while(!s.empty())
{
int v=s.top();
s.pop();
if(!vis2[v])
{
ans++;
dfs(v,adjT);
}
}
return ans;
}