Parallel Courses

There are N courses, labelled from 1 to N.

We are given relations[i] = [X, Y], representing a prerequisite relationship between course X and course Y: course X has to be studied before course Y.

In one semester you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.

Return the minimum number of semesters needed to study all courses.  If there is no way to study all the courses, return -1.

 

Example 1:

Input: N = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation: 
In the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.

Example 2:

Input: N = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation: 
No course can be studied because they depend on each other.

 

Note:

  1. 1 <= N <= 5000
  2. 1 <= relations.length <= 5000
  3. relations[i][0] != relations[i][1]
  4. There are no repeated relations in the input.

Solution:

class Solution {
    public int minimumSemesters(int N, int[][] relations) {
        List<Integer>[] edges = new List[N + 1];
        int[] inDegrees = new int[N + 1];
        Deque<Integer> zeroIns = new ArrayDeque();
        for (int i = 1; i <= N; i ++) {
            edges[i] = new ArrayList();
        }
        for (int[] rel : relations) {
            int from = rel[0];
            int to = rel[1];

            edges[from].add(to);
            inDegrees[to] ++;
        }
        for (int i = 1; i <= N; i ++) {
            if (inDegrees[i] == 0) {
                zeroIns.offerLast(i);
            }
        }        

        int step = 0;
        int count = 0;
        while (!zeroIns.isEmpty()) {
            int size = zeroIns.size();
            for (int i = 0; i < size; i ++) {
                int start = zeroIns.pollFirst();
                count ++;
                for (int next : edges[start]) {
                    inDegrees[next] --;
                    if (inDegrees[next] == 0) {
                        zeroIns.offerLast(next);
                    }
                }
            }
            step ++;
        }
        if (count == N) return step;
        return -1;
    }
}