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.
我的解法:
拓扑排序,用kahn算法解决。原理是构造一个入度队列,统计每个节点的入度,初始化的时候把入度为0的节点放入一个队列中。
然后循环下述过程:从队列poll一个数出来,把其邻接节点的入度统统减一。在减的过程中探索有没有节点此时的入度已经为0,有的话,把其加入队列中,同时对全局统计量加一。
最后,看下全局统计量是否等于给出的课程数,如果相等的话,证明无环,课程可以修完。
code:
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
//construct indegree
if(numCourses==0)return true;
int len = prerequisites.length;
if(len==0)return true;
int[] degree = new int[numCourses];
Arrays.fill(degree,0);
for(int i=0;i<len;i++){
degree[prerequisites[i][0]]++;
}
//final count
int count = 0;
Queue<Integer> qu = new LinkedList<>();
//put a zero into queue
for(int i=0;i<degree.length;i++){
if(degree[i] == 0){
qu.offer(i);
count = count+1;
}
}
while(!qu.isEmpty()){
//minus the ajance node
int temp = qu.poll();
for(int i=0; i<len;i++){
//find the ajance
if(prerequisites[i][1]==temp){
degree[prerequisites[i][0]]--;
if(degree[prerequisites[i][0]]==0){
qu.offer(prerequisites[i][0]);
count = count+1;
}
}
}
}
return count==numCourses;
//record the count
}
}