forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
30 lines (30 loc) · 846 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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> edges(numCourses);
vector<int> indegree(numCourses);
for (auto& p : prerequisites)
{
int a = p[0], b = p[1];
edges[b].push_back(a);
++indegree[a];
}
queue<int> q;
for (int i = 0; i < numCourses; ++i)
if (indegree[i] == 0)
q.push(i);
vector<int> ans;
while (!q.empty())
{
int b = q.front();
q.pop();
ans.push_back(b);
for (int a : edges[b])
{
--indegree[a];
if (indegree[a] == 0) q.push(a);
}
}
return ans.size() == numCourses ? ans : vector<int>();
}
};