From 1d7cea86eccd108e6a06e7bfac082ddca77f9978 Mon Sep 17 00:00:00 2001 From: Abhishek Yadav <31253403+AbhiY98@users.noreply.github.com> Date: Tue, 20 Nov 2018 19:00:46 +0530 Subject: [PATCH 1/2] Added Topological Sorting --- Graph/Topological-Sort.cpp | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Graph/Topological-Sort.cpp diff --git a/Graph/Topological-Sort.cpp b/Graph/Topological-Sort.cpp new file mode 100644 index 000000000..f05217209 --- /dev/null +++ b/Graph/Topological-Sort.cpp @@ -0,0 +1,45 @@ +#include +#include +#include + using namespace std; + +int n , m; // For number of Vertices (V) and number of edges (E) +vector< vector > G; +vector visited; +vector 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(){ + cin >> n >> m; + int x , y; + G.resize(n , vector()); + 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 << ' '; + } + cout << '\n'; + return 0; +} From a8ab996d27ee219cefedc645e28b21f7419d75f3 Mon Sep 17 00:00:00 2001 From: Abhishek Yadav <31253403+AbhiY98@users.noreply.github.com> Date: Wed, 20 Feb 2019 00:15:38 +0530 Subject: [PATCH 2/2] Update Topological-Sort.cpp --- Graph/Topological-Sort.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Graph/Topological-Sort.cpp b/Graph/Topological-Sort.cpp index f05217209..61a4fcd2e 100644 --- a/Graph/Topological-Sort.cpp +++ b/Graph/Topological-Sort.cpp @@ -27,18 +27,19 @@ void topological_sort() { reverse(ans.begin(), ans.end()); } int main(){ + cout << "Enter the number of vertices and the number of directed edges\n"; cin >> n >> m; int x , y; G.resize(n , vector()); for(int i = 0 ; i < n ; ++i) { cin >> x >> y; - x-- , y--; //to convert 1-indexed to 0-indexed + 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 << ' '; + cout << v + 1 << ' '; // converting zero based indexing back to one based. } cout << '\n'; return 0;