-
Notifications
You must be signed in to change notification settings - Fork 77
/
Kahn’s_Algorithm.cpp
73 lines (60 loc) · 1.89 KB
/
Kahn’s_Algorithm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Problem Statement: Given a Directed Acyclic Graph (DAG) with V vertices and E edges, Find any Topological Sorting of that Graph.
// Input Format: V = 6, E = 6
// Result: 5, 4, 0, 2, 3, 1
// Explanation: A graph may have multiple topological sortings.
// The result is one of them. The necessary conditions for the ordering are:
// According to edge 5 -> 0, node 5 must appear before node 0 in the ordering.
// According to edge 4 -> 0, node 4 must appear before node 0 in the ordering.
// According to edge 5 -> 2, node 5 must appear before node 2 in the ordering.
// According to edge 2 -> 3, node 2 must appear before node 3 in the ordering.
// According to edge 3 -> 1, node 3 must appear before node 1 in the ordering.
// According to edge 4 -> 1, node 4 must appear before node 1 in the ordering.
// The above result satisfies all the necessary conditions.
// [4, 5, 2, 3, 1, 0] and [4, 5, 0, 2, 3, 1] are also such
// topological sortings that satisfy all the conditions.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
//Function to return list containing vertices in Topological order.
vector<int> topoSort(int V, vector<int> adj[])
{
int indegree[V] = {0};
for (int i = 0; i < V; i++) {
for (auto it : adj[i]) {
indegree[it]++;
}
}
queue<int> q;
for (int i = 0; i < V; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
vector<int> topo;
while (!q.empty()) {
int node = q.front();
q.pop();
topo.push_back(node);
// node is in your topo sort
// so please remove it from the indegree
for (auto it : adj[node]) {
indegree[it]--;
if (indegree[it] == 0) q.push(it);
}
}
return topo;
}
};
int main() {
//V = 6;
vector<int> adj[6] = {{}, {}, {3}, {1}, {0, 1}, {0, 2}};
int V = 6;
Solution obj;
vector<int> ans = obj.topoSort(V, adj);
for (auto node : ans) {
cout << node << " ";
}
cout << endl;
return 0;
}