Course Schedule
You now have numCourses courses that need to be taken, labeled from 0 to numCourses - 1. You are given an array prerequisites, where prerequisites[i] = [ai, bi] indicates that to take course ai, you must first complete course bi.
For example, if you want to study course 0, you need to finish course 1 first, and we can represent it with a pair [0,1].
Return one valid order of courses so that all courses can be completed in the required order.
Example
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
这道题本质上是课程依赖关系的拓扑排序问题:把每门课看成图中的节点,先修关系看成有向边,从先修课指向后续课程。要求返回一种可行的学习顺序,如果图中存在环则无法完成全部课程。常见做法是使用 BFS 的 Kahn 算法统计入度,先把所有入度为 0 的课程加入队列,逐步弹出并更新后继课程的入度,最终得到一个拓扑序;也可以用 DFS 做后序遍历并检测环。示例中 <code>4</code> 门课和依赖 <code>[[1,0],[2,0],[3,1],[3,2]]</code> 的一个合法答案是 <code>[0,2,1,3]</code>。