-
Notifications
You must be signed in to change notification settings - Fork 738
/
Kosaraju Algorithm.cpp
83 lines (66 loc) · 1.39 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Kosaraju Algorithm - By Sameer Aggrawal
// Similar to topological sort function (dfs)
void dfs(int node,vector<int> adj[],vector<bool> &visited,stack<int> &stk)
{
visited[node] = true;
for(auto child: adj[node])
{
if(!visited[child])
{
dfs(child,adj,visited,stk);
}
}
stk.push(node);
}
void dfsRec(int node,vector<int> g[],vector<bool> &visited)
{
visited[node]=true;
for(auto child: g[node])
{
if(!visited[child])
{
dfsRec(child,g,visited);
}
}
return;
}
//Function to find number of strongly connected components in the graph.
int kosaraju(int V, vector<int> adj[])
{
int i,j;
stack<int> stk;
vector<int> result;
vector<bool> visited(V,false);
for(i=0;i<V;i++)
{
if(!visited[i])
{
dfs(i,adj,visited,stk);
}
}
while(!stk.empty())
{
result.push_back(stk.top());
stk.pop();
}
vector<int> g[V];
for(i=0;i<V;i++)
{
for(auto x: adj[i])
{
g[x].push_back(i);
}
}
for(i=0;i<V;i++) visited[i]=false;
int cnt=0;
for(i=0;i<V;i++)
{
int node=result[i];
if(!visited[node])
{
cnt++;
dfsRec(node,g,visited);
}
}
return cnt;
}