现在你总共有 n 门课需要选,记为 0 到 n-1。
在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]
给定课程总量以及它们的先决条件,返回你为了学完所有课程所安排的学习顺序。
可能会有多个正确的顺序,你只要返回一种就可以了。如果不可能完成所有课程,返回一个空数组。
示例 1: 输入: 2, [[1,0]] 输出: [0,1] 解释: 总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 [0,1] 。 示例 2: 输入: 4, [[1,0],[2,0],[3,1],[3,2]] 输出: [0,1,2,3] or [0,2,1,3] 解释: 总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。 因此,一个正确的课程顺序是 [0,1,2,3] 。另一个正确的排序是 [0,2,1,3] 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/course-schedule-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。根据207. 课程表改写相关返回的结果数组即可。
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: indegrees = [0 for _ in range(numCourses)] adjacency = [[] for _ in range(numCourses)] numCourses_ = numCourses queue = deque() # Get the indegree and adjacency of every course. for cur, pre in prerequisites: indegrees[cur] += 1 adjacency[pre].append(cur) # Get all the courses with the indegree of 0. ans = [] for i in range(len(indegrees)): if not indegrees[i]: queue.append(i) ans.append(i) # BFS TopSort. while queue: pre = queue.popleft() numCourses -= 1 for cur in adjacency[pre]: indegrees[cur] -= 1 if not indegrees[cur]: queue.append(cur) ans.append(cur) if len(ans) == numCourses_: return ans else: return []