-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCourse Schedule.cpp
More file actions
39 lines (34 loc) · 965 Bytes
/
Copy pathCourse Schedule.cpp
File metadata and controls
39 lines (34 loc) · 965 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
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> adj[numCourses];
for (auto& pre : prerequisites) {
adj[pre[1]].push_back(pre[0]);
}
vector<int>indegree(numCourses, 0);
for (int i = 0; i < numCourses; i++) {
for (auto it : adj[i]) {
indegree[it]++;
}
}
queue<int> q;
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
vector<int> topo;
while (!q.empty()) {
int node = q.front();
q.pop();
topo.push_back(node);
for (auto it : adj[node]) {
indegree[it]--;
if (indegree[it] == 0) {
q.push(it);
}
}
}
return topo.size() == numCourses;
}
};