Skip to content

Added Topological Sorting #171

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 2 commits into from
Feb 20, 2019
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
46 changes: 46 additions & 0 deletions Graph/Topological-Sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int n , m; // For number of Vertices (V) and number of edges (E)
vector< vector<int> > G;
vector<bool> visited;
vector<int> ans;

void dfs(int v) {
visited[v] = true;
for (int u : G[v]) {
if (!visited[u])
dfs(u);
}
ans.push_back(v);
}

void topological_sort() {
visited.assign(n, false);
ans.clear();
for (int i = 0; i < n; ++i) {
if (!visited[i])
dfs(i);
}
reverse(ans.begin(), ans.end());
}
int main(){
cout << "Enter the number of vertices and the number of directed edges\n";
cin >> n >> m;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add cout<<"enter number of vertices and edges = "; or something similar so the user knows what input has to be given.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed !

int x , y;
G.resize(n , vector<int>());
for(int i = 0 ; i < n ; ++i) {
cin >> x >> y;
x-- , y--; // to convert 1-indexed to 0-indexed
G[x].push_back(y);
}
topological_sort();
cout << "Topological Order : \n";
for(int v : ans) {
cout << v + 1 << ' '; // converting zero based indexing back to one based.
}
cout << '\n';
return 0;
}