【Leetcode】Course Schedule II

来源:互联网 发布:三菱plcfx3u编程手册 编辑:程序博客网 时间:2024/06/06 09:31

题目链接:https://leetcode.com/problems/course-schedule-ii/

题目:
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, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

For example:

2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

思路:
跟上题解法一样,只是增加了在过程中记录结果,这一步骤。

算法:

    public int[] findOrder(int numCourses, int[][] prerequisites) {        int preCount[] = new int[numCourses];        Queue<Integer> notPre = new LinkedList<Integer>();        int res[] = new int[numCourses];        int num = -1;// 可以拓扑排序的节点个数        // 统计每个结点作为前驱的次数        for (int i = 0; i < prerequisites.length; i++) {            preCount[prerequisites[i][0]]++;        }        // 记录出度为0的结点        for (int i = 0; i < preCount.length; i++) {            if (preCount[i] == 0) {                notPre.offer(i);                num++;                res[num] = i;            }        }        while (!notPre.isEmpty()) {// BFS            int node = notPre.poll();            for (int i = 0; i < prerequisites.length; i++) {                if (prerequisites[i][1] == node) {                    preCount[prerequisites[i][0]]--;// 删除和node有关的边                    if (preCount[prerequisites[i][0]] == 0) {// 如果出度为0                        num++;                        res[num] = prerequisites[i][0];                        notPre.offer(prerequisites[i][0]);                    }                }            }        }        return (num+1) == numCourses ? res : new int[0];    }
0 0
原创粉丝点击