-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.cpp
36 lines (27 loc) · 944 Bytes
/
solution.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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>());
vector<int> inDegree(numCourses, 0);
vector<int> result;
for(vector<int> c: prerequisites) {
inDegree[c[0]]++;
graph[c[1]].push_back(c[0]);
}
queue<int> q;
for(int i = 0; i < inDegree.size(); ++i) {
if(inDegree[i] == 0) q.push(i);
}
while(!q.empty()) {
int current = q.front();
q.pop();
result.push_back(current);
for(int node: graph[current]) {
inDegree[node]--;
if(inDegree[node] == 0) q.push(node);
}
}
if(numCourses == result.size()) return result;
return {};
}
};