forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopological sort using dfs.cpp
45 lines (44 loc) · 1013 Bytes
/
Topological sort using dfs.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
#include<bits/stdc++.h>
using namespace std;
static stack<int> s;
void addata(vector<int> grph[],int a, int b){
grph[a].push_back(b);
}
void DFS(bool visited[],vector<int> grph[],int i){
visited[i]=true;
for(int p:grph[i]){
if(visited[p]==false){
DFS(visited,grph,p);
}
}
s.push(i);
}
void topological_sort(vector<int>grph[],int v){
bool visited[v];
int i;
for(i=0;i<v;i++){
visited[i]=false;
}
for(i=0;i<v;i++){
if(visited[i]==0){
DFS(visited,grph,i);
}
}
while(!s.empty()){
cout<<s.top()<<" ";
s.pop();
}
}
int main(){
int v,e,a,b;
cout<<"Enter the number of vertices of in directed graphs"<<endl;
cin>>v;
vector<int> grph[v];
cout<<"Enter the number of edges in graph"<<endl;
cin>>e;
for(int i=0;i<e;i++){
cin>>a>>b;
addata(grph,a,b);
}
topological_sort(grph,v);
}