Question

Formatted question description: https://leetcode.ca/all/210.html

 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.

 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:
 The input prerequisites is a graph represented by a list of edges, not adjacency matrices.
    Read more about how a graph is represented.
 You may assume that there are no duplicate edges in the input prerequisites.

 @tag-graph

Algorithm

Topological Sort of directed graph, in this way, the difficulty increases,

Due to the basis of the previous one, with a slight modification, every time an array is removed from the queue, it is stored in the result.

In the end, if there is a cycle in the directed graph, the number of elements in the result is not equal to the total number of courses, then we clear the result.

Code

Java

import java.util.*;

public class Course_Schedule_II {

    public static void main(String[] args) {
        Course_Schedule_II out = new Course_Schedule_II();
        Solution s = out.new Solution();

        System.out.println(Arrays.toString(s.findOrder(2, new int[][]{ {1,0} })));
    }

    class Solution {
        public int[] findOrder(int numCourses, int[][] prerequisites) {

            if(numCourses <= 0) {
                return new int[0];
            }

            if(prerequisites == null) {
                return new int[numCourses];
            }

            int[] inDegree = new int[numCourses];
            for (int[] each: prerequisites) {
                inDegree[each[0]]++;
            }

            Queue<Integer> q = new LinkedList<>();
            for (int i = 0; i < inDegree.length; i++) {
                if (inDegree[i] == 0) {
                    q.offer(i);
                }
            }

            List<Integer> result = new ArrayList<>();
            while (!q.isEmpty()) {
                int current = q.poll();
                result.add(current);

                for (int[] each: prerequisites) {
                    if (current == each[1]) {
                        inDegree[each[0]]--;

                        if (inDegree[each[0]] == 0) {
                            q.offer(each[0]);
                        }
                    }
                }
            }

            if(!(result.size() == numCourses)) {
                return new int[0];
            }

            return result.stream().mapToInt(i -> i).toArray();
        }
    }

    class Solution2 {
        public int[] findOrder(int numCourses, int[][] prerequisites) {

            if (numCourses <= 0 || prerequisites == null) {
                return new int[0];
            }

            // construct graph
            int[] incomingCount = new int[numCourses];
            List<List<Integer>> g = new ArrayList<>(numCourses);

            constructGraph(numCourses, prerequisites, g, incomingCount);

            // bfs or dfs
            return bfs(numCourses, g, incomingCount);
        }

        private int[] bfs(int numCourses, List<List<Integer>> g, int[] incomingCount) {

            int[] result = new int[numCourses];

            Queue<Integer> q = new LinkedList<>();

            // search for starting point
            for (int i = 0; i < numCourses; i++) {
                if (incomingCount[i] == 0) {
                    q.offer(i); // could be multiple node without incoming
                }
            }

            int resultPointer = 0;
            while (!q.isEmpty()) {
                int node = q.poll();
                result[resultPointer++] = node;
                for (int each: g.get(node)) {
                    incomingCount[each]--;
                    if (incomingCount[each] == 0) {
                        q.offer(each);
                    }
                }
            }

            // @note: how to check valid result
            return resultPointer == numCourses ? result : new int[0];
        }

        private void constructGraph(int numCourses, int[][] prerequisites, List<List<Integer>> g, int[] incomingCount) {

            // empty graph
            for (int i = 0; i < numCourses; i++) {
                g.add(new ArrayList<Integer>());
            }

            for (int[] pair: prerequisites) {
                incomingCount[pair[0]]++;
                g.get(pair[1]).add(pair[0]);
            }
        }
    }
}

All Problems

All Solutions