Skip to content

Latest commit

 

History

History
164 lines (151 loc) · 5.64 KB

210. Course Schedule II.md

File metadata and controls

164 lines (151 loc) · 5.64 KB

leetcode Daily Challenge on July 18th, 2020.


Difficulty : Medium

Related Topics : DFSBFSTopological SortGraph


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.

Solution

  • mine
    • Java
      • Topological Sort & BFS Runtime: 3 ms, faster than 95.92%, Memory Usage: 40.1 MB, less than 93.57% of Java online submissions
        // O(N)time
        // O(N)space
        public int[] findOrder(int n, int[][] p) {
            int[] count = new int[n];
            List<Integer>[] list = new List[n];
            for (int i = 0; i < n; i++) {
                list[i] = new ArrayList<>();
            }
            for (int[] i : p) {
                list[i[1]].add(i[0]);
                count[i[0]]++;
            }
            LinkedList<Integer> stack = new LinkedList<>();
            boolean[] used = new boolean[n];
            for (int i = 0; i < n; i++) {
                if (count[i] == 0) {
                    stack.add(i);
                    used[i] = true;
                }
            }
            int index = 0;
            int[] res = new int[n];
            while (!stack.isEmpty()) {
                Integer remove = stack.removeFirst();
                res[index++] = remove;
                for (int i : list[remove]) {
                    if (used[i]) continue;
                    count[i]--;
                    if(count[i] == 0){
                        stack.add(i);
                        used[i] = true;    
                    }
        
                }
            }
            return index == n ? res : new int[]{};
        }
        

  • the most votes
  • BFS & DFS Runtime: 3 ms, faster than 95.92%, Memory Usage: 41.1 MB, less than 25.68% of Java online submissions
    // O(N)time
    // O(N)space
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] incLinkCounts = new int[numCourses];
        List<List<Integer>> adjs = new ArrayList<>(numCourses);
        initialiseGraph(incLinkCounts, adjs, prerequisites);
        // return solveByBFS(incLinkCounts, adjs);
        return solveByDFS(adjs);
    }
    
    private void initialiseGraph(int[] incLinkCounts, List<List<Integer>> adjs, int[][] prerequisites){
        int n = incLinkCounts.length;
        while (n-- > 0) adjs.add(new ArrayList<>());
        for (int[] edge : prerequisites) {
            incLinkCounts[edge[0]]++;
            adjs.get(edge[1]).add(edge[0]);
        }
    }
    
    private int[] solveByBFS(int[] incLinkCounts, List<List<Integer>> adjs) {
        int[] order = new int[incLinkCounts.length];
        Queue<Integer> toVisit = new ArrayDeque<>();
        for (int i = 0; i < incLinkCounts.length; i++) {
            if (incLinkCounts[i] == 0) toVisit.offer(i);
        }
        int visited = 0;
        while (!toVisit.isEmpty()) {
            int from = toVisit.poll();
            order[visited++] = from;
            for (int to : adjs.get(from)) {
                incLinkCounts[to]--;
                if (incLinkCounts[to] == 0) toVisit.offer(to);
            }
        }
        return visited == incLinkCounts.length ? order : new int[0];
    }
    
    
    private int[] solveByDFS(List<List<Integer>> adjs) {
        BitSet hasCycle = new BitSet(1);
        BitSet visited = new BitSet(adjs.size());
        BitSet onStack = new BitSet(adjs.size());
        Deque<Integer> order = new ArrayDeque<>();
        for (int i = adjs.size() - 1; i >= 0; i--) {
            if (visited.get(i) == false && hasOrder(i, adjs, visited, onStack, order) == false)
                return new int[0];
        }
        int[] orderArray = new int[adjs.size()];
        for (int i = 0; !order.isEmpty(); i++) orderArray[i] = order.pop();
        return orderArray;
    }
    
    private boolean hasOrder(int from, List<List<Integer>> adjs, BitSet visited, BitSet onStack, Deque<Integer> order) {
        visited.set(from);
        onStack.set(from);
        for (int to : adjs.get(from)) {
            if (visited.get(to) == false) {
                if (hasOrder(to, adjs, visited, onStack, order) == false) return false;
            } else if (onStack.get(to) == true) {
                return false;
            }
        }
        onStack.clear(from);
        order.push(from);
        return true;
    }