networkx图论最短路径Dijkstra Algorithm,Python

x33g5p2x  于2021-11-11 转载在 Go  
字(1.0k)|赞(0)|评价(0)|浏览(531)
  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. def my_graph():
  4. G = nx.Graph(my_g='my_graph') # 无向图
  5. nodes = ['a', 'b', 'c', 'd', 'e']
  6. G.add_nodes_from(nodes)
  7. G.add_edges_from([('a', 'b', {'weight': 1}),
  8. ('a', 'c', {'weight': 3}),
  9. ('a', 'd', {'weight': 6}),
  10. ('a', 'e', {'weight': 7}),
  11. ('b', 'c', {'weight': 1}),
  12. ('c', 'd', {'weight': 2}),
  13. ('d', 'e', {'weight': 1})])
  14. print(G.edges(data=True))
  15. print(G.nodes())
  16. START = 'a'
  17. END = 'e'
  18. path = nx.dijkstra_path(G, source=START, target=END)
  19. print('路径:', path)
  20. path_length = nx.dijkstra_path_length(G, source=START, target=END)
  21. print('距离:', path_length)
  22. pos = nx.spiral_layout(G)
  23. nx.draw(G, pos,
  24. node_color='green',
  25. node_size=300,
  26. font_size=15,
  27. font_color='black',
  28. edge_color='red',
  29. width=8,
  30. with_labels=True)
  31. my_edge_labels = nx.get_edge_attributes(G, 'weight')
  32. nx.draw_networkx_edge_labels(G, pos, edge_labels=my_edge_labels)
  33. plt.show()

运行日志:

  1. [('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})]
  2. ['a', 'b', 'c', 'd', 'e']
  3. 路径: ['a', 'b', 'c', 'd', 'e']
  4. 距离: 5

输出:

相关文章

最新文章

更多