forked from sourav-122/hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kahn's_algorithm
48 lines (44 loc) · 986 Bytes
/
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
// Given a Directed Acyclic Graph (DAG) with V
// vertices and E edges.
// Find any Topological Sorting of that Graph.
vector<int> topoSort(int V, vector<int> adj[])
{
int indeg[V];
memset(indeg,0,sizeof(indeg));
for(int i=0;i<V;i++)
{
for(auto it:adj[i])
{
indeg[it]++;
}
}
queue<int>q;
for(int i=0;i<V;i++)
{
if(indeg[i]==0)
{
q.push(i);
}
}
vector<int>v;
while(!q.empty())
{
int b=q.size();
while(b--)
{
int node=q.front();
q.pop();
v.push_back(node);
for(int child:adj[node])
{
if(--indeg[child]==0)
{
q.push(child);
}
}
}
}
return v;
}
// time complexity- O(V+E)
// space complexity- O(V)