There are numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] means that you must take course bi before course ai.
For example, the pair [0, 1] means that to take course 0 you have to take course 1 first.
Return true if you can finish all the courses, or false otherwise.
Example 1:
Input: numCourses = 2, prerequisites = [[1, 0]] Output: true Explanation: To take course 1 you need course 0 first, and course 0 needs nothing. Take course 0, then course 1.
Example 2:
Input: numCourses = 2, prerequisites = [[1, 0], [0, 1]] Output: false Explanation: Course 1 needs course 0 first, and course 0 needs course 1 first. The two courses wait for each other (a cycle), so neither of them can ever be taken.
Example 3:
Input: numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
Output: true
Explanation: Draw each pair [a, b] as an arrow b → a, from the course to take first:
0 → 1 → 3
0 → 2 → 3
Course 0 needs nothing, courses 1 and 2 need course 0, and course 3 needs both 1 and 2.
The order 0, 1, 2, 3 takes every course after all of its prerequisites (0, 2, 1, 3 works too).
An order of all the courses in which every arrow points forward is called a topological order.
All the courses can be finished exactly when such an order exists, that is, when the arrows form no cycle.
Constraints:
1 <= numCourses <= 1050 <= prerequisites.length <= 105prerequisites[i].length == 20 <= ai, bi < numCoursesai != bi- All the pairs
prerequisites[i]are distinct.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
