Skip to content

Commit a3ddfcd

Browse files
authored
Merge pull request #171 from AbhiY98/master
Added Topological Sorting
2 parents f77fd6f + a8ab996 commit a3ddfcd

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Graph/Topological-Sort.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
int n , m; // For number of Vertices (V) and number of edges (E)
7+
vector< vector<int> > G;
8+
vector<bool> visited;
9+
vector<int> ans;
10+
11+
void dfs(int v) {
12+
visited[v] = true;
13+
for (int u : G[v]) {
14+
if (!visited[u])
15+
dfs(u);
16+
}
17+
ans.push_back(v);
18+
}
19+
20+
void topological_sort() {
21+
visited.assign(n, false);
22+
ans.clear();
23+
for (int i = 0; i < n; ++i) {
24+
if (!visited[i])
25+
dfs(i);
26+
}
27+
reverse(ans.begin(), ans.end());
28+
}
29+
int main(){
30+
cout << "Enter the number of vertices and the number of directed edges\n";
31+
cin >> n >> m;
32+
int x , y;
33+
G.resize(n , vector<int>());
34+
for(int i = 0 ; i < n ; ++i) {
35+
cin >> x >> y;
36+
x-- , y--; // to convert 1-indexed to 0-indexed
37+
G[x].push_back(y);
38+
}
39+
topological_sort();
40+
cout << "Topological Order : \n";
41+
for(int v : ans) {
42+
cout << v + 1 << ' '; // converting zero based indexing back to one based.
43+
}
44+
cout << '\n';
45+
return 0;
46+
}

0 commit comments

Comments
 (0)