There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
method 1 topological sort
有严格的顺序要求,所以自然而然想到拓扑排序
输入的是边集,所以要建图才好使用拓扑排序,这里选择邻接表作为图的数据结构(声明一个vector的二维数组vector<vector> edge(numCourses);)
使用队列进行BFS搜索,进行拓扑排序
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> edge(numCourses);
int* indegree = new int[numCourses];
for (int i = 0; i < numCourses; i++)
indegree[i] = 0;
for (int i = 0; i < prerequisites.size(); i++)
{
indegree[prerequisites[i][0]]++;
edge[prerequisites[i][1]].push_back(prerequisites[i][0]);
}
queue<int> q; //保存入度为0的结点
for (int i = 0; i < numCourses; i++)
{
if (indegree[i] == 0)
q.push(i);
}
vector<int> ans;
while (!q.empty())
{
int v = q.front(); q.pop();
ans.push_back(v);
for (int i = 0; i < edge[v].size(); i++)
{
if (--indegree[edge[v][i]] == 0)
q.push(edge[v][i]);
}
}
if(ans.size() < numCourses) ans.clear();
return ans;
}
如果ans的大小小于节点个数,说明存在环
summary
- 有严格的顺序要求,使用BFS建立拓扑排序
- 本题拓扑排序是模板代码,需要牢记