207. Course Schedule

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:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. 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
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值