Last active
July 30, 2017 09:12
-
-
Save shubham100795/7a939535b975b321abf0ab2f9fab6ab4 to your computer and use it in GitHub Desktop.
find strongly connected components in a directed graph using kosaraju's algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<iostream> | |
| #include<stack> | |
| #define initial 0 | |
| #define visited 1 | |
| #define finished 2 | |
| using namespace std; | |
| int adj[10][10]; | |
| int rev_adj[10][10]; | |
| int state[10]; | |
| stack<int> st; | |
| void create_graph(int n,int m) | |
| { | |
| int i,j,k,src,dest; | |
| for(j=0;j<n;j++) | |
| { | |
| for(k=0;k<n;k++) | |
| { | |
| adj[j][k]=0; | |
| } | |
| } | |
| for(i=0;i<m;i++) | |
| { | |
| cout<<"enter the source and destination \n"; | |
| cin>>src>>dest; | |
| if(src<0||src>=n||dest<0||dest>=n) | |
| { | |
| cout<<"invalid vertex \n"; | |
| i--; | |
| } | |
| adj[src][dest]=1; | |
| } | |
| for(j=0;j<n;j++) | |
| { | |
| for(k=0;k<n;k++) | |
| { | |
| cout<<adj[j][k]<<"\t"; | |
| } | |
| cout<<endl; | |
| } | |
| } | |
| void DFS_traversal(int s,int n,int t_no) | |
| { | |
| int i; | |
| cout<<s<<"\t"; | |
| state[s]=visited; | |
| if(t_no==1) | |
| { | |
| for(i=0;i<n;i++) | |
| { | |
| if(adj[s][i]==1&&state[i]==initial) | |
| DFS_traversal(i,n,t_no); | |
| } | |
| } | |
| else | |
| { | |
| for(i=0;i<n;i++) | |
| { | |
| if(rev_adj[s][i]==1&&state[i]==initial) | |
| DFS_traversal(i,n,t_no); | |
| } | |
| } | |
| state[s]=finished; | |
| if(t_no==1) | |
| st.push(s); | |
| } | |
| void find_components(int n) | |
| { | |
| int a,b; | |
| cout<<endl<<"reverse graph--\n"; | |
| for(a=0;a<n;a++) | |
| { | |
| for(b=0;b<n;b++) | |
| { | |
| rev_adj[a][b]=adj[b][a]; | |
| } | |
| } | |
| for(a=0;a<n;a++) | |
| { | |
| for(b=0;b<n;b++) | |
| { | |
| cout<<rev_adj[a][b]<<"\t"; | |
| } | |
| cout<<endl; | |
| } | |
| cout<<"components are\n"; | |
| while(!st.empty()) | |
| { | |
| int q=st.top(); | |
| st.pop(); | |
| if(state[q]==initial) | |
| { | |
| DFS_traversal(q,n,2); | |
| cout<<endl; | |
| } | |
| } | |
| } | |
| int main() | |
| { | |
| int n,m,s,z; | |
| cout<<"enter the no of vertices \n"; | |
| cin>>n; | |
| cout<<"Enter the number of edges\n"; | |
| cin>>m; | |
| create_graph(n,m); | |
| for(z=0;z<n;z++) | |
| { | |
| state[z]=initial; | |
| } | |
| cout<<"enter the starting vertex \n"; | |
| cin>>s; | |
| cout<<endl; | |
| DFS_traversal(s,n,1); | |
| cout<<endl; | |
| for(z=0;z<n;z++) | |
| { | |
| state[z]=initial; | |
| } | |
| find_components(n); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment