跳转至

210. Course Schedule II

Leetcode Graph Depth-first Search Breath-first Search Topological Sort

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.

Example 1:

Input: 2, [[1,0]] 
Output: [0,1]
Explanation: 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].

Example 2:

Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: 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] .

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices.
  2. You may assume that there are no duplicate edges in the input prerequisites.

分析

这题意思非常简单:给出上课顺序。这道题目是207. Course Schedule的延伸,前者只需要判断所有课程是否可以完成,现在需要给出完成的顺序。那么第一步肯定是用dfs来判断课程是否可以完成,那么怎么给出顺序呢?拓扑排序。有先决条件限制的规划问题(precedence-constrained scheduling problem)是拓扑排序的典型应用。拓扑排序其实就是dfs后序的逆序(reverse postOrder)。所以可以将拓扑排序和环的判断同时进行。

private boolean hasCycle;
public int[] findOrder(int numCourses, int[][] prerequisites) {
    hasCycle = false;
    // construct a graph
    List<List<Integer>> graph = new ArrayList<>();
    for (int i = 0; i < numCourses; i++)
        graph.add(new ArrayList<Integer>());
    for (int[] prerequisite : prerequisites)
        graph.get(prerequisite[1]).add(prerequisite[0]);

    // dfs
    boolean[] mark = new boolean[numCourses];
    boolean[] onStack = new boolean[numCourses];
    List<Integer> postOrder = new ArrayList();
    for (int v = 0; v < numCourses; v++)
        if (!hasCycle & !mark[v]) 
            dfs(graph, mark, onStack, postOrder, v);

    // impossible to finish all course
    if (hasCycle) return new int[]{};
    // get reversePostOrder
    int [] reverePostOrder = new int[numCourses];
    for (int i = 0; i < numCourses; i++)
        reverePostOrder[i] = postOrder.get(numCourses - i - 1);
    return reverePostOrder;
}

private void dfs(List<List<Integer>> graph, boolean[] mark,
             boolean[] onStack, List<Integer> postOrder, int v) {
    mark[v] = true;
    onStack[v] = true;
    for (int w : graph.get(v)) {
        if (!hasCycle & !mark[w])
            dfs(graph, mark, onStack, postOrder, w);
        else if (onStack[w]) hasCycle = true;
    }
    onStack[v] = false;
    postOrder.add(v);
}