forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshreya_yadav_toposort.cpp
87 lines (73 loc) · 1.49 KB
/
shreya_yadav_toposort.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#define pb push_back
using namespace std;
int main()
{
int n = 5, edges = 10; // nodes are numbered 0,1,2,3,4;
vector<int> adjacency_list[5], result, in_degree(n, 0);
queue<int> q;
/* Graph representation in adjacency list: (feel free to input your own graph)
0 -> 2, 3, null
1 -> 2, null
2 -> 3, 4, null
3 -> null
4 -> null
The topological sort order for this graph is 0, 1, 2, 3, 4 OR 1, 0, 2, 3, 4 etc.
*/
adjacency_list[0].pb(2);
adjacency_list[0].pb(3);
adjacency_list[1].pb(2);
adjacency_list[2].pb(3);
adjacency_list[2].pb(4);
for(int i=0;i<n;i++)
{
for(int j=0;j<adjacency_list[i].size();j++)
{
int node = adjacency_list[i][j];
in_degree[node]++;
}
}
for(int i=0;i<n;i++)
{
if(in_degree[i] == 0)
q.push(i);
}
while(!q.empty())
{
int current_node = q.front();
result.pb(current_node);
q.pop();
for(int i=0;i<adjacency_list[current_node].size();i++)
{
in_degree[adjacency_list[current_node][i]]--;
if(in_degree[adjacency_list[current_node][i]] == 0)
q.push(adjacency_list[current_node][i]);
}
}
if(result.size() == n)
{
for(int i=0;i<n;i++)
{
cout<<result[i]<<" ";
}
cout<<endl;
}
else
{
cout<<"There exists a cycle in the graph"<<endl;
}
/* alternatively you can check for a cycle by checking the in-degrees
bool cycle = false;
for(int i=0;i<n;i++)
{
if(in_degree[i] != 0)
{
cycle = true;
}
}
*/
return 0;
}