先贴原题:
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.
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.
click to show more hints.
Hints:
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
Topological sort could also be done via BFS.
分析题意:每个课程都有一个前导课程,如果存在两门课程,1为2的前导课程,2也为1的前导课程,则说这个课程是不可能完成的。从本质上来说,这是一个图的编程题。而不可能完成则意味着图中存在环路。所以我们可以利用深度优先搜索来检测图中是否有环路。
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
if(prerequisites.size()==0)
return true;
for(int i = 0; i < numCourses;i++){
//把所有的节点初始值设为未访问过,也设置成都不在递归栈中
visited.push_back(false);
recursive.push_back(false);
}
for(int i = 0;i < numCourses;i++)
if(check(i,prerequisites))
return false;
return true;
}
bool check(int index,vector<pair<int, int>>& prerequisites){
if(!visited[index]){
//设置为访问过,同时入递归栈
visited[index] = true;
recursive[index] = true;
for(int i = 0; i < prerequisites.size();i++){
if(prerequisites[i].second == index){
//深度优先搜索,继续往下搜索
if(!visited[prerequisites[i].first]&&check(prerequisites[i].first,prerequisites))
return true;
//如果访问的节点已经在递归栈中,说明存在一条反向边,则说明存在环路
else if(recursive[prerequisites[i].first])
return true;
}
}
}
//不存在环路,把该点从递归栈中除去
recursive[index] = false;
return false;
}
private:
vector<bool> visited;
vector<bool> recursive;
};
时间复杂度为遍历每个课程,并且便利每个课程和每条边,所以为O(n+e);
空间复杂度,声明了两个长度为n的数组,所以为o(n);