A university offers
In a single semester a student may take any number of courses at the same time, as long as every prerequisite of each chosen course has already been completed in an earlier semester.
Find the minimum number of semesters required to complete all
Prerequisites are directed edges. This introduces directed graphs, topological ordering, and cycle detection through Kahn's algorithm, where each processing wave corresponds to one semester.
The first line contains two integers KaTeX can only parse string typed expression and KaTeX can only parse string typed expression — the number of courses and the number of prerequisite rules.
Each of the next KaTeX can only parse string typed expression lines contains two integers KaTeX can only parse string typed expression and KaTeX can only parse string typed expression, meaning course KaTeX can only parse string typed expression must be completed before course KaTeX can only parse string typed expression.
Print the minimum number of semesters needed to finish all courses. If it is impossible, print KaTeX can only parse string typed expression.
Input
4 4
1 2
1 3
2 4
3 4Output3ExplanationSemester KaTeX can only parse string typed expression: take course KaTeX can only parse string typed expression. Semester KaTeX can only parse string typed expression: take courses KaTeX can only parse string typed expression and KaTeX can only parse string typed expression together. Semester KaTeX can only parse string typed expression: take course KaTeX can only parse string typed expression. Three semesters are needed.
Example 2:
Input
3 3
1 2
2 3
3 1Output-1ExplanationThe rules require KaTeX can only parse string typed expression before KaTeX can only parse string typed expression, KaTeX can only parse string typed expression before KaTeX can only parse string typed expression, and KaTeX can only parse string typed expression before KaTeX can only parse string typed expression. This cycle can never be satisfied.
Example 3:
Input
4 0Output1ExplanationNo course has any prerequisite, so all four can be taken together in a single semester.