leetcode刷题笔记-topological sort拓扑排序(DFS)

这篇博客主要探讨了LeetCode中与拓扑排序相关的题目,如2050. Parallel Courses III、444. Sequence Reconstruction和210. Course Schedule系列。通过这些题目,博主讲解了如何检查课程先修条件中是否存在环,并给出了JAVA实现的拓扑排序模板。同时,博主提供了解决这些问题的思路和示例,帮助读者理解如何完成所有课程的正确顺序。

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

2050. Parallel Courses III

class Solution:
    def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
        indegree = collections.defaultdict(int)
        m = collections.defaultdict(set)
        for a, b in relations:
            a, b = a-1, b-1  # convert to 0 based 
            m[a].add(b)
            indegree[b] += 1
        
        # find the 0 indegree nodes
        q = []
        cost = [0] * n # months required to finish i course, it is the max cost of predecessor nodes + time[i]
        for i in range(n):
            if indegree[i] == 0:
                q.append(i)
                cost[i] = time[i]
        
        while q:
            node = q.pop(0)
            for v in m[node]:
                cost[v] = max(cost[v], cost[node] + time[v])
                indegree[v] -= 1
                if indegree[v] == 0:
                    q.append(v)
        
        return max(cost)

444. Sequence Reconstruction

class Solution:
    def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
        nodes = set([node for seq in seqs for node in seq])
        graph = {node : [] for node in nodes}
        indegree = {node:0 for node in nodes}  # 图,从上往下只能有一条路线 每次从indegree = 0 的点走 如果有2个或者以上Indgree=0的就是false, 走了这个indegree=0的点,它下面的点的indegree就-1
        
        for seq in seqs:
            for i in range(len(seq)-1):
                pre = seq[i]
                nxt = seq[i+1]
                graph[pre].append(nxt)
                indegree[nxt] += 1
        
        # find the indegree = 0 one, which is the root, should only ha
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值