LeetCode210. Course Schedule II (思路及python解法)

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 []

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值