forked from SR-Sunny-Raj/Hacktoberfest2021-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkosaraju_algo.cpp
74 lines (69 loc) · 1.26 KB
/
kosaraju_algo.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
// time:O(n+e)
//kosaraju algorithm for strongly connected component
#include<bits/stdc++.h>
using namespace std;
void dfstrverse(vector<int> &visited,vector<int>adj[],stack<int> &st,int node)
{
visited[node]=1;
for(auto it:adj[node])
{
if(!visited[it])
{
dfstrverse(visited,adj,st,it);
}
}
st.push(node);
}
void revdfs(vector<int> &visited,vector<int>rev[],stack<int> &st,int node)
{
visited[node]=1;
cout<<node<<" ";
for(auto it:rev[node])
{
if(!visited[it])
{
revdfs(visited,rev,st,it);
}
}
}
int main()
{
int v,e;
cin>>v>>e;
vector<int>adj[v+1];
for(int i=0;i<e;i++)
{
int x,y;
cin>>x>>y;
adj[x].push_back(y);
}
vector<int>visited(v+1,0);
stack<int>st;
for(int i=1;i<=v;i++)
{
if(!visited[i])
{
dfstrverse(visited,adj,st,i);
}
}
vector<int>rev[v+1];
for(int i=1;i<=v;i++)
{
visited[i]=0;
for(auto it:adj[i])
{
rev[it].push_back(i);
}
}
while(!st.empty())
{
int node=st.top();
st.pop();
if(!visited[node])
{
revdfs(visited,rev,st,node);
cout<<endl;
}
}
return 0;
}