【刷题】Leetcode 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?

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        if(prerequisites.length == 0)
            return true;
        int[] indegree = new int[numCourses];
        Arrays.fill(indegree, -1);
        HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
        int count = 0;
        for(int[] p: prerequisites){
            if(!map.containsKey(p[0])){
                indegree[p[0]] = 0;
                map.put(p[0], new ArrayList<Integer>());
                count++;
            }
            if(!map.containsKey(p[1])){
                indegree[p[1]] = 1;
                map.put(p[1], new ArrayList<Integer>());
                count++;
            }
            else{
                indegree[p[1]]++;
            }
            map.get(p[0]).add(p[1]);
        }
        
        Queue<Integer> q = new LinkedList<Integer>();
        for(int i = 0; i < indegree.length; i++){
            if(indegree[i] == 0){
                q.offer(i);
            }
        }
        
        while(!q.isEmpty()){
            int temp = q.poll();
            count--;
            if(map.get(temp) != null){
                for(int a: map.get(temp)){
                    if(--indegree[a] == 0){
                        q.offer(a);
                    }
                }
            }
           
        }
        return count == 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值