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:

Given n = 2, prerequisites = [[1,0]]
Return [0,1]

Given n = 4, prerequisites = [1,0],[2,0],[3,1],[3,2]]
Return [0,1,2,3] or [0,2,1,3]

Solution:

First, we need to count the number of the in-degree for each vertex or course. Then we add all vertex with degree 0 to an FIFO queue.

After that, we could start an BFS search for the 0 degree vertex. During this process, we need to reduce the number of degree by one for each connected vertex (BFS searched vertex).

Code:

public class Solution {
    /**
     * @param numCourses a total of n courses
     * @param prerequisites a list of prerequisite pairs
     * @return the course order
     */
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        ArrayList<Integer>[] edges = new ArrayList[numCourses];
        int[] degrees = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            edges[i] = new ArrayList<>();
        }

        for (int i = 0; i < prerequisites.length; i++) {
            degrees[prerequisites[i][0]]++;
            edges[prerequisites[i][1]].add(prerequisites[i][0]);
        }

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

        int[] res = new int[numCourses];
        int count = 0;
        while (!q.isEmpty()) {
            int course = q.poll();
            res[count++] = course;
            for (int nextCourse : edges[course]) {
                degrees[nextCourse]--;
                if (degrees[nextCourse] == 0) {
                    q.offer(nextCourse);
                }
            }
        }
        if (count == numCourses) {
            return res;
        }
        return new int[0];
    }
}

results matching ""

    No results matching ""