Description
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Example 1:
1 | Input: numCourses = 2, prerequisites = [[1,0]] |
Example 2:
1 | Input: numCourses = 2, prerequisites = [[1,0],[0,1]] |
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
0 <= ai, bi < numCourses
All the pairs prerequisites[i] are unique.
Solutions
- Prerequesite is stored in courses: [following courses]
- The number of pre-courses required for each course is stored in pre_nums
- Traverse pre_nums, if the number of pre-courses of the current course is 0, append the course to the queue
- When all pre_nums[nxt] are processed, enter all courses with an entry degree of 0 (meaning subjects without pre-course requirements) into the queue, and run the “topological sort” once, if all the number of prerequisite courses equals 0, stating that all courses can be completed.
1 | # O(m+n) time | O(m+n) space |