Parallel Courses
Examples
Example 1:
Input: n = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation:
Example 2:
Input: n = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation:
Example 1:
Input: n = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation:
Example 2:
Input: n = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation:
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei.
In one semester, you can take any number of courses as long as you have finished all the prerequisites in the previous semester for the courses you are taking.
Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1.
In the first semester, courses 1 and 2 are taken. In the second semester, course 3 is taken.
No course can be taken because they are prerequisites of each other.
1 <= n <= 50001 <= relations.length <= 5000relations[i].length == 21 <= prevCoursei, nextCoursei <= nprevCoursei != nextCoursei[prevCoursei, nextCoursei] are unique.