-
Notifications
You must be signed in to change notification settings - Fork 0
/
Course Schedule.cpp
43 lines (35 loc) · 995 Bytes
/
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
class Solution
{
public:
vector<int> findOrder(int n, int m, vector<vector<int>> prerequisites)
{
vector<vector<int>> g(n);
vector<int> in(n, 0);
for(int i = 0; i < m; i++){
g[prerequisites[i][1]].push_back(prerequisites[i][0]);
++in[prerequisites[i][0]];
}
queue<int> q;
vector<int> ans;
for(int i = 0; i < n; i++){
if(in[i] == 0){
q.push(i);
ans.push_back(i);
}
}
while(!q.empty()){
int node = q.front();
q.pop();
for(auto child : g[node]){
--in[child];
if(in[child] == 0){
q.push(child);
ans.push_back(child);
}
}
}
if(ans.size() < n)
ans.clear();
return ans;
}
};