-
Notifications
You must be signed in to change notification settings - Fork 3
/
210.cpp
27 lines (27 loc) · 884 Bytes
/
210.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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
vector<int> inDegrees(numCourses, 0);
for (auto& prerequisite : prerequisites) {
inDegrees[prerequisite[0]]++;
graph[prerequisite[1]].push_back(prerequisite[0]);
}
queue<int> q;
for (int i = 0; i < numCourses; ++i) {
if (inDegrees[i] == 0) q.push(i);
}
vector<int> res;
while (!q.empty()) {
int node = q.front();
res.push_back(node);
q.pop();
for (auto& neighbor : graph[node]) {
inDegrees[neighbor]--;
if (inDegrees[neighbor] == 0) q.push(neighbor);
}
}
if (res.size() != numCourses) return {};
return res;
}
};