栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python实现拓扑排序并绘图

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python实现拓扑排序并绘图

 绘图需要:

1. 需要安装graphviz软件,配置bin文件夹到环境变量
windows:
下载地址:https://graphviz.gitlab.io
Linux:
# yum下载graphviz软件:
yum -y install graphviz
2. 需要安装python的graphviz模块
pip install graphviz
from collections import defaultdict

from graphviz import Digraph


class Graph:
    def __init__(self, vertices):
        self.graph = defaultdict(list)
        self.V = vertices

    def addEdge(self, u, v):
        self.graph[u].append(v)

    def topologicalSortUtil(self, v, visited, stack):

        visited[v] = True

        for node in self.graph[v]:
            if visited[node] == False:
                self.topologicalSortUtil(node, visited, stack)

        stack.insert(0, v)

    def topologicalSort(self):
        visited = {}
        for key, values in self.graph.items():
            visited[key] = False
            for val in values:
                visited[val] = False
        stack = []

        for node in visited.keys():
            if visited[node] == False:
                self.topologicalSortUtil(node, visited, stack)

        return stack

def draw_graph(node_relations):
    dot = Digraph(comment='node graph', filename='blueprintNodeGraph-neato', format='png', engine='neato')
    dot.attr(
        'node',
        shape='box', style='rounded,filled',
        fixedsize='false',
        fontname='Microsoft YaHei', fontsize='12')
    node_size = 0
    for relation in node_relations:
        node_size += 1
        # wrapsize = 12
        # dot.node(textwrap.fill(node_name, wrapsize))
        dot.edge(relation[0], relation[1], len='3')
        print(f"{relation[0]} -> {relation[1]}")
    dot.render(directory='doctest-output', view=True).replace('\', '/')


if __name__ == '__main__':
    node_relations = (('A', 'B'),
                      ('A', 'C'),
                      ('B', 'C'),
                      ('C', 'D'),
                      ('C', 'E'),
                      ('E', 'F'),
                      ('E', 'G'),
                      ('E', 'H'))
    # 拓扑排序
    g = Graph(8)
    for a, b in node_relations:
        g.addEdge(a, b)
    topo_list = g.topologicalSort()
    print(topo_list)
    # 绘图
    draw_graph(node_relations)

执行后输出:

# output
['A', 'B', 'C', 'E', 'H', 'G', 'F', 'D']
A -> B
A -> C
B -> C
C -> D
C -> E
E -> F
E -> G
E -> H

 拓扑图:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932083.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号