207. Course Schedule
Medium
143874FavoriteShare
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?
Example 1:
Input: 2, [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]] Output: false Explanation: 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.
方法一:dfs染色
class Solution {
public:
vector<int> vec[12345];
int color[12345];//-1代表还未访问,0代表正在访问,1代表访问完成
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
for (int i = 0; i < prerequisites.size(); i++){
pair<int,int> p = prerequisites[i];
vec[p.second].push_back(p.first);
}
memset(color,-1,sizeof(color));
for (int i = 0; i < numCourses; i++){
if(color[i] == -1){
if(!dfs(i)){
return false;
}
}
}
return true;
}
bool dfs(int u){
color[u] = 0;//正在访问染成0
for (int i = 0; i < vec[u].size(); i++){
int v = vec[u][i];
if(color[v] == 0){//如果一个结点还为访问完成就又被访问到了,则代表有环。
return false;
} else if(color[v] == -1){
if(!dfs(v)){
return false;
}
}
}
color[u] = 1;//访问完毕染成1
return true;
}
};
方法二:拓扑排序:
class Solution {
public:
int indegree[12345];
vector<int> vec[12345];
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
memset(indegree, 0, sizeof(indegree));
for (int i = 0; i < prerequisites.size(); i++){
pair<int,int> p = prerequisites[i];
vec[p.second].push_back(p.first);
indegree[p.first]++;
}
queue<int> que;
for (int i = 0; i < numCourses; i++){
if(!indegree[i]){
que.push(i);
}
}
while(!que.empty()){
int u = que.front();
que.pop();
for (int i = 0; i < vec[u].size(); i++){
int v = vec[u][i];
indegree[v]--;
if(!indegree[v]){
que.push(v);
}
}
}
for (int i = 0; i < numCourses; i++){
if(indegree[i]){
return false;
}
}
return true;
}
};