码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 207. Course Schedule

时间:2020-02-03 13:33:02      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:nis   ssi   course   div   lse   als   label   schedule   ISE   

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.

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        if (numCourses == 0 || prerequisites == null) {
            return false;
        }
        int[] indegree = new int[numCourses];
        for (int[] pres : prerequisites) {
            indegree[pres[0]] += 1;
        }
        int res = numCourses;
        
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < indegree.length; i++) {
            if (indegree[i] == 0) {
                queue.offer(i);
            }
        }
        while(!queue.isEmpty()) {
            Integer cur = queue.poll();
            res -= 1;
            
            for (int[] pres: prerequisites) {
                if (pres[1] == cur) {
                    // for a -> b, minus degree of a
                    indegree[pres[0]] -= 1;
                    if (indegree[pres[0]] == 0) {
                        queue.offer(pres[0]);
                    }
                }
            }
        }
        return res == 0;
    }
}

 

[LC] 207. Course Schedule

标签:nis   ssi   course   div   lse   als   label   schedule   ISE   

原文地址:https://www.cnblogs.com/xuanlu/p/12255214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!