30 Day Challenge Day 16 | Leetcode 210. Course Schedule II
题解
Medium
Topological Sort
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>());
vector<int> in(numCourses);
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);
}
vector<int> ret;
while(!q.empty()) {
int t = q.front();
q.pop();
ret.push_back(t);
for(auto next : graph[t]) {
in[next]--;
if(in[next] == 0) q.push(next);
}
}
if(ret.size() < numCourses) return {};
return ret;
}
};