题目
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, is it possible for you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
题目大意
你需要去学习一组课程,这些课程的标号为0-n-1。一些课程有先修课程,例如为了选修课程0,你需要去选修课程1,上述的例子可以表示为一个pair[0,1]。现在给你一个课程数和一组先修课程的列表,请你判断下你有没有可能完成所有的课程。例如2,[[1,0]]。总共就2门课给你选,你要完成课程1就得先完成课程0。所以这组课程你是可以完成的。
再如2, [[1,0],[0,1]],总共有2门课程可以选择,为了完成课程1你得先完成课程0,并且为了完成课程0你得完成课程1,这显然是矛盾的,所以你是不可能完成的
题目分析
这题很显然,也就是大多数数据结构的书上在讲拓扑排序时引用的例子,所以很自然的联想到使用拓扑排序,代码如下:
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
/*init the graph*/
for(int i=0;i<numCourses;i++){
m_graph.emplace_back(vector<int>());
visited.emplace_back(vector<bool>());
indegree.emplace_back(0);
for(int j=0;j<numCourses;j++){
m_graph[i].emplace_back(0);
visited[i].emplace_back(false);
}
}
for(int i=0;i<prerequisites.size();i++){
m_graph[prerequisites[i].second][prerequisites[i].first]=1;
indegree[prerequisites[i].first]++;
}
return topSort();
}
bool topSort(){
int count=0;
stack<int> m_stack;
for(int i=0;i<indegree.size();i++)
if(!indegree[i]){
m_stack.push(i);
count++;
}
while(!m_stack.empty()){
int index=m_stack.top();
m_stack.pop();
for(int i=0;i<m_graph.size();i++){
if(m_graph[index][i]){
indegree[i]--;
if(indegree[i]==0)
m_stack.push(i),count++;
}
}
}
return count==m_graph.size();
}
private:
vector<vector<int>> m_graph;
vector<vector<bool>> visited;
vector<int> indegree;
};