Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <list>
- using namespace std;
- int v,t;
- int matrix[100][100];
- int clr[100], dis[100], fin[100], prev[100];
- int t_edge,b_edge,f_edge,c_edge;
- list <int> tp_sort;
- list <int> :: iterator it;
- void DFS();
- void DFS_visit(int s);
- int main ()
- {
- int r, c, n, s;
- int edge = 1;
- cout<<"Input no of vertices: ";
- cin>>v;
- do{
- cout<<"Edge "<<edge<<": ";
- cin>>r>>c;
- if(r>v || c>v)
- cout<<"Invalid input"<<endl;
- else{
- matrix[r][c] = 1;
- edge++;
- }
- }while(r != 0 && c!=0);
- DFS();
- if(b_edge > 0)
- cout<<endl<<"Topological sort can't be determined!!!(Cyclic Graph)"<<endl;
- else{
- cout<<endl<<endl<<"Topological sort : ";
- for(it = tp_sort.begin(); it != tp_sort.end(); it++)
- cout<< *it << " ";
- }
- cout<<endl;
- return 0;
- }
- void DFS ()
- {
- int i;
- t =0;
- t_edge = 0;
- b_edge = 0;
- f_edge = 0;
- c_edge = 0;
- for(i=0; i<=v; i++)
- {
- clr[i] = 0;
- dis[i] = 2000000;
- fin[i] = 2000000;
- prev[i] = -1;
- }
- for(i=1; i<=v; i++)
- {
- if(clr[i] == 0)
- DFS_visit(i);
- }
- //printing
- cout<<endl<<"vertex : ";
- for(i=1; i<=v; i++)
- cout<<i<<" ";
- cout<<endl<<"d[u] : ";
- for(i=1; i<=v; i++)
- cout<<dis[i]<<" ";
- cout<<endl<<"f[u] : ";
- for(i=1; i<=v; i++)
- cout<<fin[i]<<" ";
- //edges
- cout<<endl<<"No of tree edge: "<< t_edge;
- cout<<endl<<"No of back edge: "<< b_edge;
- cout<<endl<<"No of forward edge: "<< f_edge;
- cout<<endl<<"No of cross edge: "<< c_edge;
- }
- void DFS_visit(int s)
- {
- int i;
- clr[s] = 1;
- dis[s] = ++t;
- for(i=1; i<=v; i++)
- {
- if(matrix[s][i] == 1 && clr[i] == 2)
- {
- if (dis[s] < dis[i]){
- f_edge++;
- cout<<s<<"-"<<i<<" : Forward Edge"<<endl;
- }
- else{
- c_edge++;
- cout<<s<<"-"<<i<<" : Cross Edge"<<endl;
- }
- }
- else if(matrix[s][i] == 1 && clr[i] == 1){
- b_edge++;
- cout<<s<<"-"<<i<<" : Back Edge"<<endl;
- }
- else
- {
- if(matrix[s][i] == 1 && clr[i] == 0)
- {
- prev[i] = s;
- cout<<s<<"-"<<i<<" : Tree Edge"<<endl;
- t_edge++;
- DFS_visit(i);
- }
- }
- }
- clr[s] = 2;
- fin[s] = ++t;
- tp_sort.push_front(s);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement