leetcode210. 课程表 II
题目链接:https://leetcode-cn.com/problems/course-schedule-ii/
- 思路:拓扑排序,注意建图初始化
class Solution {
public:
vector<vector<int>>map;
vector<int>index;
queue<int>q;
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<int>ans;
map.resize(numCourses);
index.resize(numCourses);
//建图
for(int i=0;i<prerequisites.size();i++)
{
int x=prerequisites[i][1];
int y=prerequisites[i][0];
//cout<<x<<"+"<<y<<endl;
map[x].push_back(y);
index[y]++;
}
//遍历
for(int i=0;i<index.size();i++)
{
if(index[i]==0)
{
q.push(i);
}
}
while(!q.empty())
{
int k=q.front();
//cout<<k<<endl;
q.pop();
ans.push_back(k);
for(int i=0;i<map[k].size();i++)
{
index[map[k][i]]--;
if(index[map[k][i]]==0)
{
q.push(map[k][i]);
}
}
}
if(ans.size()!=numCourses)
{
ans.clear();
return ans;
}
return ans;
}
};