forked from Masked-coder11/gfg-POTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.01.2024.cpp
50 lines (42 loc) · 1.1 KB
/
23.01.2024.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
//User function Template for C++
class Solution
{
public:
vector<int> findOrder(int n, int m, vector<vector<int>> prerequisites)
{
//code here
//create a graph and an indegree array simultaneously
vector<int>inDegree(n,0);
vector<int>adj[n];
for(int i=0;i<m;i++){
adj[prerequisites[i][1]].push_back(prerequisites[i][0]);
inDegree[prerequisites[i][0]]++;
}
//kahn's algo
queue<int>q;
for(int i=0;i<n;i++){
if(inDegree[i]==0){
q.push(i);
}
}
vector<int>ans;
while(!q.empty()){
int node=q.front();
q.pop();
ans.push_back(node);
for(auto it:adj[node]){
inDegree[it]--;
if(inDegree[it]==0){
q.push(it);
}
}
}
if(ans.size()<n){
//a cycle is present
return {};
}
else{
return ans;
}
}
};