Description:
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 <= N <= 5000
1 <= relations.length <= 5000
relations[i][0] != relations[i][1]
There are no repeated relations in the input.
Analysis:
Use BFS to implement the topological sort of this directed graph and use an ArrayList to store the sorted numbers of nodes.
After sorting, if the size of the ArrayList is not equal to N, that means there must exist a cycle in the graph, so we just return -1; If the size of the ArrayList is equal to N, then we return the level we have traversed.
Code:
class Solution {
public int minimumSemesters(int N, int[][] relations) {
int[] inDegree = new int[N+1]; // inDegree[i] represents the in-degree of vi;
List<List<Integer>> graph = new ArrayList<>(); // graph.get(i) storing all the labels of vertices that vi pointing to
Queue<Integer> queue = new LinkedList<>();
List<Integer> sortedList = new ArrayList<>();
for(int i = 0; i < N+1; i++) {
graph.add(new ArrayList<Integer>());
}
for(int[] relation: relations) {
inDegree[relation[1]]++;
graph.get(relation[0]).add(relation[1]);
}
for(int i = 1; i < N+1; i++) {
if(inDegree[i] == 0) {
queue.offer(i);
}
}
int semester = 0;
while(queue.peek() != null) {
semester += 1;
int size = queue.size();
for(int i = 0; i < size; i++) {
int k = queue.poll();
sortedList.add(k);
for(int j: graph.get(k)) {
inDegree[j]--;
if(inDegree[j] == 0) {
queue.offer(j);
}
}
}
}
if(sortedList.size() != N) {
return -1;
}else{
return semester;
}
}
}