-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopological Sort(Kahn's Algorithm).cpp
More file actions
75 lines (67 loc) · 1.35 KB
/
Copy pathTopological Sort(Kahn's Algorithm).cpp
File metadata and controls
75 lines (67 loc) · 1.35 KB
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
74
75
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
void topoSort(vector<vector < int>> &adjList, int n, vector< int > &inDegree)
{
vector<int> res;
queue<int> q;
for (int i = 0; i < n; i++)
{
if (inDegree[i] == 0)
{
q.push(i);
}
}
while (!q.empty())
{
int node = q.front();
res.push_back(node);
q.pop();
int neighbours = adjList[node].size();
for (int i = 0; i < neighbours; i++)
{
int neighbourNode = adjList[node][i];
inDegree[neighbourNode]--;
if (inDegree[neighbourNode] == 0)
{
q.push(neighbourNode);
}
}
}
for (int i = 0; i < n; i++)
{
cout << res[i] << " ";
}
}
void addEdge(vector<vector < int>> &adjList, int u, int v)
{
adjList[u].push_back(v);
}
int main()
{
int n, m;
cout << "Enter number of nodes and edges: " << endl;
cin >> n >> m;
vector<int> color(n, -1);
vector<vector < int>> adjList(n);
vector<bool> visited(n, false);
cout << "Enter edges: " << endl;
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
addEdge(adjList, u, v);
}
vector<int> inDegree(n, 0);
for (int i = 0; i < n; i++)
{
int neighbours = adjList[i].size();
for (int j = 0; j < neighbours; j++)
{
int neighbourNode = adjList[i][j];
inDegree[neighbourNode]++;
}
}
topoSort(adjList, n, inDegree);
}