forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parallel-courses.cpp
36 lines (34 loc) · 960 Bytes
/
parallel-courses.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
// Time: O(|V| + |E|)
// Space: O(|E|)
class Solution {
public:
int minimumSemesters(int N, vector<vector<int>>& relations) {
unordered_map<int, vector<int>> g;
vector<int> in_degree(N);
for (const auto& r : relations) {
g[r[0] - 1].emplace_back(r[1] - 1);
++in_degree[r[1] - 1];
}
queue<pair<int, int>> q;
for (int i = 0; i < N; ++i) {
if (!in_degree[i]) {
q.emplace(1, i);
}
}
int result = 0;
int count = N;
while (!q.empty()) {
int level, u;
tie(level, u) = q.front(); q.pop();
--count;
result = level;
for (const auto& v : g[u]) {
--in_degree[v];
if (!in_degree[v]) {
q.emplace(level+1, v);
}
}
}
return count == 0 ? result : -1;
}
};