题目
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.
click to show more hints.
Subscribe to see which companies asked this question
思路
简单分析一下就知道,这就是在一个图中找有没有环,且所有点都能访问到。这个题目就是拓扑排序的典型应用。
思路很简单,维护一个队列,存放可以访问到的节点。再用一个map,key为被依赖的节点,val为依赖key节点的所有节点的list。当key节点被加入到可访问到队列时,遍历所有val节点,看这些节点因为key节点的可访问是否满足了访问条件,也就是它们还有没有别的依赖。
所以为表示方便,我定义了一个入度(inDegree),入度为0的节点就是可以被加入到可访问队列中的节点,因为它们不需要任何前提节点就可以访问,有点类似与大学中的大一上学期学的英语和高数,它们是所有其他课程的先修课程,它们之前不需要修任何课程。
然后遍历依赖高数、英语课程的节点,看他们是否因为这两门先修课程的可到达从而变得可到达,判断依据仍然为入度。当先修课程可到达时,依赖它们的课程的入度-1,当入度为0时,就是它们的先修课程已经全部修完,那么它们就变成可到达了,就把它们加入队列。直到队列为空,判断是否全部可到达即可。
代码
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> pre(numCourses);
int N = prerequisites.size();
vector<int> inDegree(numCourses,0);
for (int i=0;i<N;++i){
auto p = prerequisites[i];
inDegree[p.first]++;
pre[p.second].push_back(p.first);
}
queue<int> que;
for (int i=0;i<numCourses;++i){
if (inDegree[i]==0) que.push(i);
}
int count=0;
while(!que.empty()){
int acc=que.front();
que.pop();
++count;
for (auto st:pre[acc]){
if (inDegree[st]==1){
que.push(st);
}
inDegree[st]--;
}
}
return count==numCourses;
}