Leetcode 210. 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].

思路:
基本同207题是一样的,只是要求返回的结果不同,参见207.

public int[] findOrder(int numCourses, int[][] prerequisites) {
    //tip 后面的是前置条件
    int[] preCount = new int[numCourses];
    List<List<Integer>> unlock = new ArrayList<>();
    for (int i = 0; i < numCourses; i++) {
        unlock.add(new ArrayList<>());
    }

    for (int i = 0; i < prerequisites.length; i++) {
        int[] pre = prerequisites[i];
        preCount[pre[0]] += 1;
        unlock.get(pre[1]).add(pre[0]);
    }

    //use queue to search and count
    int cnt = 0;
    Queue<Integer> q = new LinkedList<>();
    for (int i = 0; i < numCourses; i++) {
        if (preCount[i] == 0) {
            q.offer(i);
        }
    }
    int[] res = new int[numCourses];
    while (!q.isEmpty()) {
        int num = q.poll();
        res[cnt] = num;
        cnt++;
        List<Integer> subs = unlock.get(num);
        for (int i = 0; i < subs.size(); i++) {
            int next = subs.get(i);
            preCount[next] -= 1;
            if (preCount[next] == 0) {
                q.offer(next);
            }
        }
    }

    return cnt == numCourses ? res : new int[0];
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/a5387fd7d0f5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞