[LeetCode] Course Schedule II

210. Course Schedule II

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

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<int> res;
unordered_map<int, int> cnt;
unordered_map<int, list<int>> course;
int chk = 0;
for(auto& p : prerequisites) {
course[p.back()].push_back(p.front());
cnt[p.front()]++;
}
for(int i = 0; i < numCourses; i++) {
if(!cnt.count(i)) res.push_back(i);
}
while(!cnt.empty()) {
int sz = res.size();
if(sz == chk) return {};
for(;chk < sz; chk++) {
for(auto& c : course[res[chk]]) {
if(!--cnt[c]) {
res.push_back(c);
cnt.erase(c);
}
}
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/12/PS/LeetCode/course-schedule-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.