-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_LCR_113_findOrder.cc
More file actions
44 lines (42 loc) · 896 Bytes
/
Problem_LCR_113_findOrder.cc
File metadata and controls
44 lines (42 loc) · 896 Bytes
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
40
41
42
43
44
#include <queue>
#include <vector>
using namespace std;
// @sa https://leetcode.cn/problems/course-schedule-ii/
// @sa Problem_0210_findOrder.cc
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites)
{
vector<int> indegrees(numCourses);
vector<vector<int>> graph(numCourses);
for (auto& e : prerequisites)
{
graph[e[1]].push_back(e[0]);
indegrees[e[0]]++;
}
queue<int> q;
for (int i = 0; i < numCourses; i++)
{
if (indegrees[i] == 0)
{
q.push(i);
}
}
vector<int> ans;
while (!q.empty())
{
int cur = q.front();
q.pop();
ans.push_back(cur);
for (int next : graph[cur])
{
if (--indegrees[next] == 0)
{
q.push(next);
}
}
}
return ans.size() == numCourses ? ans : vector<int>{};
}
};