207. Course Schedule

    public static boolean canFinish(int numCourses, int[][] prerequisites) {
        // 参数检查
        if (prerequisites == null) {
            return false;
        }
        int len = prerequisites.length;
        if (numCourses <= 0 || len == 0) {
            return true;
        }
        // 记录每个course的prerequisites的数量
        int[] pCounter = new int[numCourses];
        for (int i = 0; i < len; i++) {
            pCounter[prerequisites[i][0]]++;
        }
        // 用队列记录可以直接访问的course
        LinkedList queue = new LinkedList();
        for (int i = 0; i < numCourses; i++) {
            if (pCounter[i] == 0) {
                queue.add(i);
            }
        }
        // 取出队列的course,判断
        int numNoPre = queue.size();
        while (!queue.isEmpty()) {
            int top = queue.remove();
            for (int i = 0; i < len; i++) {
                // 该course是某个course的prerequisites
                if (prerequisites[i][1] == top) {
                    pCounter[prerequisites[i][0]]--;
                    if (pCounter[prerequisites[i][0]] == 0) {
                        numNoPre++;
                        queue.add(prerequisites[i][0]);
                    }
                }
            }
        }
        return numNoPre == numCourses;
    }

你可能感兴趣的:(207. Course Schedule)