class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>>adj(numCourses);
vector<int>indegrees(numCourses);
for(int i=0;i<prerequisites.size();++i){
for(int j=0;j<prerequisites[i].size();++j){
indegrees[prerequisites[i][0]]++;
adj[prerequisites[i][1]].push_back(prerequisites[i][0]);
}
}
vector<int>Order;
for(int i=0;i<numCourses;++i){
if(indegrees[i]==0) //入度为0
Order.emplace_back(i);
}
int i=0;
while(i<Order.size()){
int courseIdx = Order[i];
i++;
for(int j=0;j<adj[courseIdx].size();++j){
indegrees[adj[courseIdx][j]]--;
if(indegrees[adj[courseIdx][j]]==0){
Order.emplace_back(adj[courseIdx][j]);
}
}
}
return Order.size()==numCourses?Order:vector<int>{};
}
};
210. 课程表 II
最新推荐文章于 2024-02-17 01:07:07 发布