zoukankan      html  css  js  c++  java
  • [LC] 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.

    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;
        }
    }
  • 相关阅读:
    Rain 学习自用贴
    連休計画
    091207 晴
    记下London奥运我喜欢的几首歌
    20世纪最好的10个算法(转)
    一日一美女:告诉你什么是斐波那契螺旋线
    矩阵鞍点的寻找
    日本の物語
    a new start~ s!
    Photoshop CS5运用色彩原理去除半透明水印(转)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12255214.html
Copyright © 2011-2022 走看看