210. Course Schedule II
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.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1] .
Example 2:
Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both
courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .
Note:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
解题思路
这道题解题思路与207题是一样的,都是通过拓扑排序来判断图中是否有环路。不同之处在于,这道题目要输出拓扑排序的序列,如果图中有环则输出为空vector。只需在拓扑排序时,将队头元素输出到结果队列中即可。
代码如下:
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
graph.resize(numCourses);
seq.resize(0);
vector<int> in_degree(numCourses, 0);
for(int i = 0; i < prerequisites.size(); i++) {
int first = prerequisites[i].first;
int second = prerequisites[i].second;
graph[second].push_back(first);
in_degree[prerequisites[i].first]++;
}
bool exist = true;
vector<int> zero_degree;
for(int i = 0; i < numCourses; i++) {
if(in_degree[i] == 0) {
zero_degree.push_back(i);
}
}
if(zero_degree.size() == 0) {
exist = false;
return seq;
}
queue<int> q;
for(int i = 0; i < zero_degree.size(); i++) {
q.push(zero_degree[i]);
}
int count = 0;
while(q.size() != 0) {
int v = q.front(); // 从队列中取出一个顶点
seq.push_back(v);
q.pop();
++count;
for(int i = 0; i < graph[v].size(); i++) {
in_degree[graph[v][i]] = in_degree[graph[v][i]] - 1;
if(in_degree[graph[v][i]] == 0) {
q.push(graph[v][i]);
}
}
}
if(count != numCourses) {
exist = false;
}
if(exist == true)
return seq;
seq.clear();
return seq;
}
private:
vector<vector<int>> graph;
vector<int> seq;
};