networkx图论最短路径Dijkstra Algorithm,Python

x33g5p2x  于2021-11-11 转载在 Go  
字(1.0k)|赞(0)|评价(0)|浏览(468)
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

输出:

相关文章

最新文章

更多