From 77ba693cea9094b596ba3328c794e379fb5ae634 Mon Sep 17 00:00:00 2001 From: Aashish <37924603+aashishtri@users.noreply.github.com> Date: Fri, 22 May 2020 19:43:50 +0530 Subject: [PATCH] Create topological_sort_by_kahns_algo.cpp (#778) * Create topological_sort_by_kahns_algo.cpp implementation of topological sorting by kahn's algo * Update topological_sort_by_kahns_algo put c system headers before c++ system headers * Update topological_sort_by_kahns_algo.cpp improves syntax (tabs/whitespaces etc) * Update topological_sort_by_kahns_algo.cpp removed errors * Update graph/topological_sort_by_kahns_algo.cpp improved syntax Co-authored-by: Christian Clauss * Fix indentation * Fix include order Co-authored-by: Christian Clauss --- graph/topological_sort_by_kahns_algo.cpp | 68 ++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 graph/topological_sort_by_kahns_algo.cpp diff --git a/graph/topological_sort_by_kahns_algo.cpp b/graph/topological_sort_by_kahns_algo.cpp new file mode 100644 index 000000000..eda2a74bc --- /dev/null +++ b/graph/topological_sort_by_kahns_algo.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include + +int *topoSortKahn(int N, std::vector adj[]); + +int main() { + int nodes, edges; + std::cin >> edges >> nodes; + if (edges == 0 || nodes == 0) + return 0; + int u, v; + + std::vectorgraph[nodes]; + // create graph + // example + // 6 6 + // 5 0 5 2 2 3 4 0 4 1 1 3 + + for (int i = 0; i < edges; i++) { + std::cin >> u >> v; + graph[u].push_back(v); + } + + int *topo = topoSortKahn(nodes, graph); + // topologically sorted nodes + for (int i = 0; i < nodes; i++) { + std::cout << topo[i] << " "; + } +} + +int* topoSortKahn(int V, std::vector adj[]) { + std::vectorvis(V+1, false); + std::vectordeg(V+1, 0); + for (int i = 0; i < V; i++) { + for (int j = 0; j < adj[i].size(); j++) { + deg[adj[i][j]]++; + } + } + std::queueq; + for (int i = 0; i < V; i++) { + if (deg[i] == 0) { + q.push(i); + vis[i] = true; + } + } + int *arr = new int[V+1]; + memset(arr, 0, V+1); + int count = 0; + while (!q.empty()) { + int cur = q.front(); + q.pop(); + arr[count] = cur; + count++; + for (int i = 0; i < adj[cur].size(); i++) { + if (!vis[adj[cur][i]]) { + deg[adj[cur][i]]--; + if (deg[adj[cur][i]] == 0) { + q.push(adj[cur][i]); + vis[adj[cur][i]] = true; + } + } + } + } + return arr; +}