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实现)

  • 相关阅读:
    -lpopt is not found while cross compiling for aarch64
    设置进程的cpu亲和性
    在ARM64位开发板上兼容ARM32位的可执行程序
    ARM开发板上查看动态库或者可执行程序的依赖关系
    交叉编译tmux
    使用PSCI机制的SMP启动分析
    将qemu使用的设备树dump出来
    故障review的一些总结
    理解Compressed Sparse Column Format (CSC)
    统计分析工程的依赖项
  • 原文地址:https://www.cnblogs.com/sight-tech/p/13217092.html
Copyright © 2011-2022 走看看