-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathTopological sort using Kahn's algorithm
59 lines (51 loc) · 1.28 KB
/
Topological sort using Kahn's algorithm
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
vector<int> topological_sorting(vector<vector<int>> graph) {
vector <int> indegree(graph.size(), 0);
queue<int> q;
vector<int> solution;
for(int i = 0; i < graph.size(); i++) {
for(int j = 0; j < graph[i].size(); j++)
{
//iterate over all edges
indegree[ graph[i][j] ]++;
}
}
//enqueue all nodes with indegree 0
for(int i = 0; i < graph.size(); i++)
{
if(indegree[i] == 0) {
q.push(i);
}
}
//remove one node after the other
while(q.size() > 0) {
int currentNode = q.front();
q.pop();
solution.push_back(currentNode);
for(int j = 0; j < graph[currentNode].size(); j++)
{
//remove all edges
int newNode = graph[currentNode][j];
indegree[newNode]--;
if(indegree[newNode] == 0)
{
//target node has now no more incoming edges
q.push(newNode);
}
}
}
return solution;
}
int main()
{
int n,v1,v2;
cin>>n;
vector<vector<int>> graph;
for(int i=1;i<=n;i++)
{
cin>>v1>>v2;
g.addEdge(v1, v2);
}
cout << " Topological Sort of the given graph \n";
g.topologicalSort();
return 0;
}