Skip to content

Create Topological sort using dfs.cpp #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 1, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Graph/Topological sort using dfs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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);
}