zoukankan      html  css  js  c++  java
  • [Python]图的遍历-拓扑排序

    在有向无环图DAG中, 使用拓扑排序,将获得一个包含所有顶点的一个列表组合, 因此可以用来遍历DAG。

    步骤

    1. 从 DAG 图中选择一个 没有前驱(即入度为0)的顶点并输出。
    2. 从图中删除该顶点和所有以它为起点的有向边。
    3. 重复 1 和 2 直到当前的 DAG 图为空或当前图中不存在无前驱的顶点为止。后一种情况说明有向图中必然存在环。

    在这里插入图片描述

    可以得到拓扑排序后的结果是 { 1, 2, 4, 3, 5 }。

    通常,一个有向无环图可以有一个或多个拓扑排序序列

    代码

    import itertools
    
    
    def topological_sort(graph):
        in_degree_dict = dict.fromkeys(graph.keys(), 0)
        flattened_values = list()  # ['B', 'C', 'A', 'C', 'D', 'A'...
        [flattened_values.extend(value) for value in graph.values()]
        for key, group in itertools.groupby(sorted(flattened_values), lambda x: x):
            in_degree_dict[key] = len(list(group))
    
        result = list()
        if not all(list(map(lambda val: val >= 1, in_degree_dict.values()))):
            # if not all in degree values greater than 1
            # = at least one degree equals to 0, continue or stop
            candidates = [key for key in in_degree_dict if in_degree_dict[key] == 0]
            while len(candidates) > 0:
                candidate = candidates.pop()
                result.append(candidate)
                for node in graph[candidate]:
                    in_degree_dict[node] -= 1
    
                in_degree_dict.pop(candidate)
                candidates.extend([key for key in in_degree_dict if in_degree_dict[key] == 0])
        else:
            print("U need build a graph with one node in-degree equals 0 at least")
        return result
    
    
    if __name__ == '__main__':
        graph_dict = {
            "A": {"B": 5, "D": 1},
            "B": {"C": 2, "D": 1},
            "C": {"E": 8},
            "D": {"C": 4, "E": 3},
            "E": {}
        }
    
        for k, v in graph_dict.items():
            graph_dict[k] = list(v.keys())
    
        # {
        # 'A': ['B', 'C'],
        # 'B': ['A', 'C', 'D'],
        # 'C': ['A', 'B', 'D', 'E'],
        # 'D': ['B', 'C', 'E', 'F'],
        # 'E': ['C', 'D'],
        # 'F': ['D']
        # }
    
        path = topological_sort(graph_dict)
        print(path)
    
    

    参考

    什么是拓扑排序(Topological Sorting)
    拓扑排序(python实现)

  • 相关阅读:
    linux查看存储盘
    aix中hd5对应什么设备?
    (转)Python 操作 Windows 粘贴板
    eclipse非主窗口的停靠(正常), 恢复, 最小化, 最大化的切换
    (转)HTML5 本地数据库(SQLite) 示例
    [译] 如何像 Python 高手一样编程?
    scrapy递归下载网站
    eclipse快捷键以及使用技巧大全
    python任意编码转utf8或者unicode
    apache快速配置简易网站
  • 原文地址:https://www.cnblogs.com/sight-tech/p/13217092.html
Copyright © 2011-2022 走看看