There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1] .
这个题思路和LeetCode207. Course Schedulehttps://blog.youkuaiyun.com/AIpush/article/details/103372810思路是一样的,只不过记录一下学习课程的顺序。
需要注意的就是如果不能所有课程全学,返回[]。
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
forward = {i:set() for i in range(numCourses)}
backward = collections.defaultdict(set)
for i,j in prerequisites:
forward[i].add(j)
backward[j].add(i)
queue = collections.deque([node for node in forward if len(forward[node])==0])
final=list(queue.copy())
while queue:
node = queue.popleft()
for bac in backward[node]:
forward[bac].remove(node)
if len(forward[bac])==0:
queue.append(bac)
final.append(bac)
forward.pop(node)
if len(final)==numCourses:
return final
return []

本文深入探讨了课程排序问题,给出了一种基于拓扑排序的解决方案。通过实例展示如何确定课程的先修顺序,确保所有课程能按正确顺序完成。特别关注了当无法完成全部课程时的处理方式。
382

被折叠的 条评论
为什么被折叠?



