AlgoFrames

Course schedule

Standard · Write code · about 12 min

There are numCourses courses numbered 0 to numCourses − 1. Each pair [a, b] in prerequisites means course b must be taken before course a. Return true if every course can be finished, and false if the requirements make that impossible.

Example 1

Input:

[4,[[1,0],[2,0],[3,1],[3,2]]]

Output:

true

Take 0, then 1 and 2, then 3.

Example 2

Input:

[3,[[1,0],[2,1],[0,2]]]

Output:

false

0 before 1, 1 before 2 and 2 before 0: a cycle.

Constraints

  • 1 ≤ numCourses ≤ 500
  • 0 ≤ prerequisites.length ≤ 2000
  • 0 ≤ a, b < numCourses

Learn the idea first: Cycle detection in undirected and directed graphs, a visual lesson.

More Cycle detection in undirected and directed graphs problems