[LeetCode] Parallel Courses

1136. Parallel Courses

You are given an integer n which indicates that we have n courses, labeled from 1 to n. You are also given an array relations where relations[i] = [a, b], representing a prerequisite relationship between course a and course b: course a has to be studied before course b.

In one semester, you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.

Return the minimum number of semesters needed to study all courses. If there is no way to study all the courses, return -1.

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
class Solution {
public:
int minimumSemesters(int n, vector<vector<int>>& relations) {
vector<list<int>> course(n + 1, list<int>());
vector<set<int>> require(n + 1, set<int>());
unordered_set<int> need;
queue<int> q;
int semester = 0;
for(auto relation : relations) {
course[relation[0]].push_back(relation[1]);
require[relation[1]].insert(relation[0]);
}

for(int i = 1; i <= n; i++) {
need.insert(i);
if(require[i].empty()) {
q.push(i);
}
}

while (!q.empty()) {
int size = q.size();
for(int i = 0; i < size; i++) {
int study = q.front();
q.pop();
need.erase(study);
for(auto next : course[study]) {
require[next].erase(study);
}
}

for(auto haveTo : need) {
if(require[haveTo].empty()) {
q.push(haveTo);
}
}
semester++;
}

return need.empty() ? semester : -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/29/PS/LeetCode/parallel-courses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.