-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse_Schedule_II.cpp
39 lines (39 loc) · 1002 Bytes
/
Course_Schedule_II.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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<int>indegree(numCourses,0);
vector<int>adj[numCourses];
for(auto e : prerequisites){
indegree[e[0]]++;
adj[e[1]].push_back(e[0]);
}
queue<int>q;
for(int i = 0; i < numCourses; i++){
if(indegree[i] == 0){
q.push(i);
}
}
vector<int>ans;
if(q.size() == 0){
return {};
}
while(!q.empty()){
int x = q.front();
q.pop();
ans.push_back(x);
for(auto j: adj[x]){
if(indegree[j] == 0){
continue;
}
indegree[j]--;
if(indegree[j] == 0){
q.push(j);
}
}
}
if(ans.size() == numCourses){
return ans;
}
return {};
}
};