Parallel Courses
There are n courses, numbered from 1 to n. Each pair [before, after] in relations means course before must be completed in an earlier semester than course after.
In one semester you can take any number of courses, as long as every prerequisite of each of them was completed in an earlier semester.
Return the minimum number of semesters needed to complete every course, or -1 if it can't be done.
Constraints
1 <= n <= 50000 <= relations.length <= 50001 <= before, after <= nandbefore !== after- A pair can appear more than once
Examples
Example 1
Input: n = 4, relations = [[1,2],[1,3],[3,4]] Output: 3
Semester 1: course 1. Semester 2: courses 2 and 3, which both only needed 1. Semester 3: course 4, which needed 3.
Example 2
Input: n = 3, relations = [[1,2],[2,3],[3,1]] Output: -1
1 → 2 → 3 → 1 is a loop, so none of these courses can ever be started: -1.
Example 3
Input: n = 5, relations = [] Output: 1
Nothing depends on anything, so all five courses fit in one semester.
JavaScript you'll use: Graphs and grids in JavaScript Arrays: create, read, update
/**
* @param {number} n
* @param {number[][]} relations
* @return {number}
*/
function minimumSemesters(n, relations) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.