题目:
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.
- 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.
思路:
这是一道拓扑排序的题目。我们的思路是首先根据先修课程的要求构建出来一张图,并且记录每个图的入度(indegree)。然后每次取出一个入度为0的顶点,作为当前可以选修的课程,同时更新和该课程构成先修关系的其它课程的入度值。如果我们做了n遍,每次都可以选出入度为0的顶点,则说明该图存在一个合法的拓扑排序,所以返回true。否则如果在某一次循环中,发现已经无法找到入度为0的顶点,这说明我们遇到了cycle,该图没有合法的拓扑排序,所以返回false。
我们下面实现的拓扑排序是基于BFS的。提示说用DFS也可以实现,我也记得算法课上老师讲了用DFS实现拓扑排序的思路,不过早已经还给老师了。。。有兴趣的读者可以戳提示中给出的视频链接。
代码:
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph(numCourses, unordered_set<int>());
vector<int> indegree(numCourses, 0);
for(auto pre : prerequisites) { // initialize the graph
if(graph[pre.second].count(pre.first) == 0) {
graph[pre.second].insert(pre.first);
indegree[pre.first]++;
}
}
for(int i = 0, j = 0; i < numCourses; i++) {
for(j = 0; j < numCourses; j++) { // find the course that can be taken now
if(indegree[j] == 0) {
break;
}
}
if(j == numCourses) {
return false;
}
--indegree[j]; // update the indegree related to j
for(auto p : graph[j]) {
--indegree[p];
}
}
return true;
}
};