-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse Schedule.cpp
46 lines (39 loc) · 1.05 KB
/
Course Schedule.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
/*
Problem Link: https://practice.geeksforgeeks.org/problems/course-schedule/1
*/
class Solution
{
public:
vector<int> findOrder(int n, int m, vector<vector<int>> prerequisites)
{
//code here
vector<int> adj[n];
for(auto it: prerequisites){
adj[it[1]].push_back(it[0]);
}
vector<int> indegree(n, 0);
vector<int> ans;
queue<int> q;
for(int i=0; i<n; i++){
for(auto adjNode: adj[i]){
indegree[adjNode]++;
}
}
for(int i=0; i<n; i++){
if(indegree[i] == 0) q.push(i);
}
while(!q.empty()){
int node= q.front();
q.pop();
ans.push_back(node);
for(auto adjNode: adj[node]){
indegree[adjNode]--;
if(indegree[adjNode] == 0){
q.push(adjNode);
}
}
}
if(ans.size() == n) return ans;
return {};
}
};