美文网首页
拓扑排序模板

拓扑排序模板

作者: madao756 | 来源:发表于2020-03-05 21:05 被阅读0次

    0X00 模板

    直接拿 207 的题解吧

    from collections import deque
    class Solution:
        def canFinish(self, numCourses: int,prerequisites: List[List[int]]) -> bool:
            indegrees = [0 for _ in range(numCourses)]
            adjacency = [[]for _ in range(numCourses)]
    
            # 构造入度表和拓扑
            for cur, pre in prerequisites:
                indegrees[cur] += 1
                adjacency[pre].append(cur)
            
            # 构造 0 入度队列
            queue = deque()
            for i in range(numCourses):
                if indegrees[i] == 0: queue.append(i)
            
            # BFS 拓扑排序
            while queue:
                pre = queue.popleft()
                numCourses -= 1
                # pre 后面的都减一
                for  follow in adjacency[pre]:
                    indegrees[follow] -= 1
                    if not indegrees[follow]: queue.append(follow)
            
            return not numCourses
    
    

    0X01 注意事项

    暂无

    0X02 相关题目

    相关文章

      网友评论

          本文标题:拓扑排序模板

          本文链接:https://www.haomeiwen.com/subject/teahrhtx.html