原题:来自leetcode的https://leetcode.com/problems/course-schedule/
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.
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> visited(numCourses, false);//记录每个节点是否已经被访问过,访问过,且没有环,就改成2,使用过程中,将其置1
vector<vector<int>> graph(numCourses);
for(int i=0; i<prerequisites.size(); i++){//创建拓扑排序的说结构,这里选择动态二维数组实现的数据结构
graph[prerequisites[i].second].push_back(prerequisites[i].first);
}
for(int i=0; i<numCourses; i++){
if(visited[i]==0 && !judge(visited, i, graph))
return false;
}
return true;
}
bool judge(vector<int> &visited, int idxCourses, vector<vector<int>> & graph){//使用dfs实现是否有环的判断
if(visited[idxCourses]==1)//如果发现为1,表示从idxCourses出发又回到了idxCourses
return false;
visited[idxCourses]=1;//改变颜色为1
for(auto it=graph[idxCourses].begin(); it!=graph[idxCourses].end(); it++){
if(!judge(visited, *it, graph))
return false;
}
visited[idxCourses]=2;//表示从当前节点除法不会差生环
return true;
}
};