[LeetCode] Course Schedule

207. Course Schedule

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 true if you can finish all courses. Otherwise, return false.

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
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> vs(numCourses, 0);
vector<list<int>> vl(numCourses, list<int>());
queue<int> q;
int cnt = 0;
for(auto& p : prerequisites) {
vs[p.front()]++;
vl[p.back()].push_back(p.front());
}
for(int i = 0 ; i < numCourses; i++) {
if(!vs[i])
q.push(i), cnt++;
}
while(q.size()) {
int c = q.front();
q.pop();
for(auto req : vl[c]) {
if(!--vs[req])
q.push(req), cnt++;
}
}

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