30 Day Challenge Day 16 | Leetcode 207. Course Schedule
题解
Medium
方法:Topological Sort
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>());
vector<int> in(numCourses, 0);
for(auto& pre : prerequisites) {
graph[pre[1]].push_back(pre[0]);
in[pre[0]]++;
}
queue<int> q;
for(int i = 0; i < numCourses; i++) {
if(in[i] == 0) q.push(i);
}
while(!q.empty()) {
int t = q.front();
q.pop();
for(auto i : graph[t]) {
in[i]--;
if(in[i] == 0) q.push(i);
}
}
for(auto x : in) {
if(x != 0) return false;
}
return true;
}
};