LeetCode 207. Course Schedule
Medium
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.
题意
选课问题,给定课程依赖列表,判断该依赖列表是否合理。其实就是判断有向图是否有环,以课程作为节点,课程之间的依赖关系作为有向边。以边列表表示的有向图,判定是否存在环路。
思路
拓扑排序。如果有向图中有环,则不能进行拓扑排序。因此按拓扑排序的思路求解,最后判断是否有剩余节点未排序即可。
拓扑排序的算法流程
- 栈S初始化;累加器count初始化;
- 扫描顶点表,将没有前驱(即入度为0)的顶点压栈;
- 当栈S非空时循环
3.1 vj=退出栈顶元素;输出vj;累加器加1;
3.2 将顶点vj的各个邻接点的入度减1;
3.3 将新的入度为0的顶点入栈;
- if (count<vertexNum) 输出有回路信息;
讨论拓扑排序算法的时间复杂度,记有向图的节点个数为V, 边个数为E. 考虑有向图无环即可以拓扑排序的情形,在整个算法执行过程中,每个节点入栈一次出栈一次,维护栈过程<伪代码1.><伪代码3.3>复杂度O(V). 入度减1<伪代码3.2>过程总共执行E次。因此,拓扑排序算法总的时间复杂度为O(V+E).
代码
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> adj(numCourses, vector<int>()); // adjacent list from from_id to to_id_set
vector<int> indegree(numCourses, 0); // in-degree
for (auto edge: prerequisites) {
adj[edge[0]].push_back(edge[1]);
indegree[edge[1]]++;
}
int sum = 0; // sum of nodes in topoSort
vector<int> zerodegree;
for (int i=0; i<numCourses; ++i) {
if (indegree[i] == 0) {
zerodegree.push_back(i);
++sum;
}
}
while (!zerodegree.empty()) { // topoSort
int i = zerodegree.back();
zerodegree.pop_back();
for (auto v: adj[i]) {
if (!(--indegree[v])) {
zerodegree.push_back(v);
++sum;
}
}
}
return sum == numCourses;
}
};