-
Notifications
You must be signed in to change notification settings - Fork 1
/
Course Schedule.cpp
38 lines (33 loc) · 1.07 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
class Solution {
public:
vector<int> findOrder(int n, int m, vector<vector<int>> prerequisites) {
vector<int> result;
vector<int> inDegree(n, 0);
vector<vector<int>> graph(n, vector<int>());
for (auto prerequisite : prerequisites) {
graph[prerequisite[1]].push_back(prerequisite[0]);
inDegree[prerequisite[0]]++;
}
queue<int> q;
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int current = q.front();
q.pop();
result.push_back(current);
for (int neighbor : graph[current]) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0) {
q.push(neighbor);
}
}
}
if (result.size() != n) {
return vector<int>();
}
return result;
}
};