原题链接在这里:https://leetcode.com/problems/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 <= N <= 5000
1 <= relations.length <= 5000
relations[i][0] != relations[i][1]
- There are no repeated relations in the input.
题解:
Let inDegree denotes prereq count.
And have preToDe to map prereq to dependency.
Then perform topological sort, for each level of BFS, level++.
Eventually check if the courses taken == N, if yes, then return level. Otherwise, return -1.
Time Complexity: O(N + relations.length).
Space: O(N).
AC Java:
1 class Solution { 2 public int minimumSemesters(int N, int[][] relations) { 3 int [] inArr = new int[N + 1]; 4 HashMap<Integer, HashSet<Integer>> preToDe = new HashMap<>(); 5 for(int [] re : relations){ 6 inArr[re[1]]++; 7 preToDe.putIfAbsent(re[0], new HashSet<Integer>()); 8 preToDe.get(re[0]).add(re[1]); 9 } 10 11 int count = 0; 12 int level = 0; 13 LinkedList<Integer> que = new LinkedList<>(); 14 for(int i = 1; i <= N; i++){ 15 if(inArr[i] == 0){ 16 que.add(i); 17 } 18 } 19 20 while(!que.isEmpty()){ 21 int size = que.size(); 22 while(size-- > 0){ 23 int cur = que.poll(); 24 count++; 25 HashSet<Integer> nexts = preToDe.getOrDefault(cur, new HashSet<Integer>()); 26 for(int next : nexts){ 27 inArr[next]--; 28 if(inArr[next] == 0){ 29 que.add(next); 30 } 31 } 32 } 33 34 level++; 35 } 36 37 return count == N ? level : -1; 38 } 39 }