forked from Vishal1003/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkahn's algorithm
More file actions
52 lines (41 loc) · 961 Bytes
/
kahn's algorithm
File metadata and controls
52 lines (41 loc) · 961 Bytes
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
// KAHN'S ALGORITHM FOR TOPSORT ORDERING
// IT USES THE CONCEPT OF INDEGREE
#include<bits/stdc++.h>
using namespace std;
vector<int> ar[10001];
vector<int> ans;
int inDegree[10001];
void kahn(int n)
{
queue<int> q;
for(int i=1;i<=n;++i)
if(inDegree[i]==0)
q.push(i);
while(!q.empty())
{
int curr = q.front();
ans.push_back(curr);
q.pop();
for(int child : ar[curr])
{
inDegree[child]--;
if(inDegree[child]==0)
q.push(child);
}
}
}
int main()
{
int n , m , a , b;
cout<<"Enter the number of vertices and number of edges: ";
cin>>n>>m;
for(int i=1;i<=n;++i) inDegree[i] = 0;
cout<<"\nEnter the values of graph:\n";
while(m--)
cin>>a>>b , ar[a].push_back(b) , inDegree[b]++;
kahn(n);
cout<<"\nTop sort order is:\n";
for(int i=0;i<ans.size();++i)
cout<<ans[i]<<" ";
return 0;
}