Skip to content

Commit 7164a7c

Browse files
authored
Merge pull request kothariji#35 from incognito1729/master
Create Topological sort using dfs.cpp
2 parents d169d31 + edd5cd2 commit 7164a7c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Graph/Topological sort using dfs.cpp

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
static stack<int> s;
4+
void addata(vector<int> grph[],int a, int b){
5+
grph[a].push_back(b);
6+
}
7+
8+
void DFS(bool visited[],vector<int> grph[],int i){
9+
visited[i]=true;
10+
for(int p:grph[i]){
11+
if(visited[p]==false){
12+
DFS(visited,grph,p);
13+
}
14+
}
15+
s.push(i);
16+
}
17+
void topological_sort(vector<int>grph[],int v){
18+
bool visited[v];
19+
int i;
20+
for(i=0;i<v;i++){
21+
visited[i]=false;
22+
}
23+
for(i=0;i<v;i++){
24+
if(visited[i]==0){
25+
DFS(visited,grph,i);
26+
}
27+
}
28+
while(!s.empty()){
29+
cout<<s.top()<<" ";
30+
s.pop();
31+
}
32+
}
33+
int main(){
34+
int v,e,a,b;
35+
cout<<"Enter the number of vertices of in directed graphs"<<endl;
36+
cin>>v;
37+
vector<int> grph[v];
38+
cout<<"Enter the number of edges in graph"<<endl;
39+
cin>>e;
40+
for(int i=0;i<e;i++){
41+
cin>>a>>b;
42+
addata(grph,a,b);
43+
}
44+
topological_sort(grph,v);
45+
}

0 commit comments

Comments
 (0)