Problem 518707 · medium · Phase 05 Advanced Algorithms & Graphs

Minimum Rounds to Finish All Tasks

topological sort · bfs layers · scheduling

There are n tasks numbered 1 .. n and a list relations where [a, b] means task a must be finished in an earlier round than task b. In one round you may perform any number of tasks, as long as all their prerequisites were finished in previous rounds.

Return the minimum number of rounds needed to finish every task, or -1 if it is impossible.

Examples

Input:  n = 3, relations = [[1, 3], [2, 3]]
Output: 2
Explanation: round 1: tasks 1 and 2; round 2: task 3.

Input:  n = 3, relations = [[1, 2], [2, 3], [3, 1]]
Output: -1

Constraints

  • 1 <= n <= 10**4, 0 <= len(relations) <= 3 * 10**4
  • Target: O(V + E) time.

Goals

  • Process a DAG level by level and count the levels
  • Return a sentinel when a cycle makes the schedule impossible
Starting Python…