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 []
  • 相关阅读:
    高可用性GRE+IPSEC中心—分支
    高可用性GRE+IPSEC中心—分支
    高可用性GRE+IPSEC中心—分支
    mysql数据库移植
    mysql数据库移植
    mysql数据库移植
    mysql数据库移植
    Linux 查看进程资源--ps、top命令
    比特币底层设计剖析
    比特币的P2P网络协议
  • 原文地址:https://www.cnblogs.com/ChevisZhang/p/12843502.html
Copyright © 2011-2022 走看看