zoukankan      html  css  js  c++  java
  • 207.210 课程表 / 检测图是否是 有向无环图(DAG)使用方法为广度遍历,拓扑排序,入度法

     本题为leetcode 207 210题 

    思路:

      1.本题求课程学习路径,即  9021 -> 9024 -> 9417 这种顺序

      2.观察可知 课程学习路劲为有向图, 如果无环则可输出,有环则返回False

    方法:

      1. 遍历所有二元对,确定0 - n-1门课程的入度

      2. 顺便将所有课程的进阶课程加入List

      3.  将所有入度为0的课程加入 队列(保证先进先出),并把其进阶课程的入度-1,如果减后入度==0,则也加入queue

      4. 最后 如果 出queue的个数 = 总数,则说明无环。

    代码:

    from collections import deque
    class Solution:
        def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
            #
            indegrees = [0 for _ in range(numCourses)]
            adjacency = [[] for _ in range(numCourses)]
            queue = deque()
            res = []
            # 比如 学3 0为前置课, 则 Indegrees[3]++ pre[0].append(3)
            for curStudy,prerequisite in prerequisites:
                indegrees[curStudy] += 1
                adjacency[prerequisite].append(curStudy)
            for index,value in enumerate(indegrees):
                if value == 0:
                    queue.append(index)
            while queue:
                # 多门课的前置课 或 单独的课
                curIndex = queue.popleft()
                res.append(curIndex)
                numCourses-=1
                for index in adjacency[curIndex]:
                    indegrees[index] -=1
                    if indegrees[index] == 0:
                        queue.append(index)
            if not numCourses:
                return res
            else:
                return []
  • 相关阅读:
    pymongo中的连接操作:Connection()与MongoClient()
    Dynamics CRM2016 新功能之从CRM APP通过电子邮件发送页面链接
    [开发工具]_[Sublime Text 2]_[配置C++编译执行环境]
    struts2 全局拦截器,显示请求方法和參数
    A. Polo the Penguin and Strings
    linux驱动之LED驱动_1
    dbgrid控件如何能在左边显示行号?
    软件提示“没有活动事务”原因以及解决办法
    刷新dbgrid 而不失去当前行位置
    用ClientDataSet更新数据表,怎样自动生成行号? [问题点数:40分]
  • 原文地址:https://www.cnblogs.com/ChevisZhang/p/12843502.html
Copyright © 2011-2022 走看看