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.
- 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.
思路:拓扑排序。也是有效的检测图中是否有环的方法。
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
vector<int> indegree(numCourses, 0);
for (auto edge : prerequisites){
graph[edge.second].push_back(edge.first);
indegree[edge.first]++;
}
queue<int> Q;
for (int i = 0; i < numCourses; i++){
if (indegree[i] == 0)
Q.push(i);
}
int count = 0;
while (!Q.empty()){
int u = Q.front();
Q.pop();
count++;
for (auto v : graph[u]){
--indegree[v];
if (indegree[v] == 0)
Q.push(v);
}
}
return count == numCourses;
}
};
二刷:
第二道是要求输出路径的,根据第二道的代码,简单修改,就是判断结果路径的结点数是否等于课程数,如果不等,就返回false,等于就返回true。
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> result;
vector<int> pushDegree(numCourses, 0);//入度表
vector<vector<int>> requisties(numCourses);//制约表
queue<int> myqueue;//0入度队列
for (auto iter : prerequisites){
pushDegree[iter.first]++;
requisties[iter.second].push_back(iter.first);
}
for (int i = 0; i < numCourses; i++){
if (pushDegree[i] == 0)
myqueue.push(i);
}
while (!myqueue.empty()){
int cur = myqueue.front();
myqueue.pop();
result.push_back(cur);
for (int i = 0; i < requisties[cur].size(); i++){
pushDegree[requisties[cur][i]]--;
if (pushDegree[requisties[cur][i]] == 0)
myqueue.push(requisties[cur][i]);
}
}
if (result.size() != numCourses)
return false;
return true;
}
};