TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
topological_sort_by_kahns_algo.cpp
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <queue>
5#include <vector>
6
7std::vector<int> topoSortKahn(int N, const std::vector<std::vector<int> > &adj);
8
9int main() {
10 int nodes = 0, edges = 0;
11 std::cin >> edges >> nodes;
12 if (edges == 0 || nodes == 0) {
13 return 0;
14 }
15 int u = 0, v = 0;
16
17 std::vector<std::vector<int> > graph(nodes);
18 // create graph
19 // example
20 // 6 6
21 // 5 0 5 2 2 3 4 0 4 1 1 3
22
23 for (int i = 0; i < edges; i++) {
24 std::cin >> u >> v;
25 graph[u].push_back(v);
26 }
27
28 std::vector<int> topo = topoSortKahn(nodes, graph);
29 // topologically sorted nodes
30 for (int i = 0; i < nodes; i++) {
31 std::cout << topo[i] << " ";
32 }
33}
34
35std::vector<int> topoSortKahn(int V,
36 const std::vector<std::vector<int> > &adj) {
37 std::vector<bool> vis(V + 1, false);
38 std::vector<int> deg(V + 1, 0);
39 for (int i = 0; i < V; i++) {
40 for (int j : adj[i]) {
41 deg[j]++;
42 }
43 }
44 std::queue<int> q;
45 for (int i = 0; i < V; i++) {
46 if (deg[i] == 0) {
47 q.push(i);
48 vis[i] = true;
49 }
50 }
51 std::vector<int> arr(V + 1, 0);
52 int count = 0;
53 while (!q.empty()) {
54 int cur = q.front();
55 q.pop();
56 arr[count++] = cur;
57 for (int i : adj[cur]) {
58 if (!vis[i]) {
59 deg[i]--;
60 if (deg[i] == 0) {
61 q.push(i);
62 vis[i] = true;
63 }
64 }
65 }
66 }
67 return arr;
68}
int main()
Main function.
Graph Algorithms.