networkx图论最短路径Dijkstra Algorithm,Python

Posted zhangphil

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了networkx图论最短路径Dijkstra Algorithm,Python相关的知识,希望对你有一定的参考价值。

import networkx as nx
import matplotlib.pyplot as plt


def my_graph():
    G = nx.Graph(my_g='my_graph')  # 无向图

    nodes = ['a', 'b', 'c', 'd', 'e']
    G.add_nodes_from(nodes)

    G.add_edges_from([('a', 'b', {'weight': 1}),
                      ('a', 'c', {'weight': 3}),
                      ('a', 'd', {'weight': 6}),
                      ('a', 'e', {'weight': 7}),
                      ('b', 'c', {'weight': 1}),
                      ('c', 'd', {'weight': 2}),
                      ('d', 'e', {'weight': 1})])

    print(G.edges(data=True))
    print(G.nodes())

    START = 'a'
    END = 'e'

    path = nx.dijkstra_path(G, source=START, target=END)
    print('路径:', path)
    path_length = nx.dijkstra_path_length(G, source=START, target=END)
    print('距离:', path_length)

    pos = nx.spiral_layout(G)
    nx.draw(G, pos,
            node_color='green',
            node_size=300,
            font_size=15,
            font_color='black',
            edge_color='red',
            width=8,
            with_labels=True)
    my_edge_labels = nx.get_edge_attributes(G, 'weight')
    nx.draw_networkx_edge_labels(G, pos, edge_labels=my_edge_labels)
    plt.show()

运行日志:

[('a', 'b', {'weight': 1}), ('a', 'c', {'weight': 3}), ('a', 'd', {'weight': 6}), ('a', 'e', {'weight': 7}), ('b', 'c', {'weight': 1}), ('c', 'd', {'weight': 2}), ('d', 'e', {'weight': 1})]
['a', 'b', 'c', 'd', 'e']
路径: ['a', 'b', 'c', 'd', 'e']
距离: 5

输出:

以上是关于networkx图论最短路径Dijkstra Algorithm,Python的主要内容,如果未能解决你的问题,请参考以下文章

图论最短路径Floyed算法和Dijkstra算法

图论最短路——dijkstra

图论最短路径问题(图的绘制以及Dijkstra算法和Bellman‐Ford算法)

图论最短路径问题(图的绘制以及Dijkstra算法和Bellman‐Ford算法)

图论Dijkstra Algorithm在2D空间平面网格节点图选择最短路径,networkx,Python

networkx图论Dijkstra Algorithm最短路径实现,Python