请查看NetworkX库。
在GitHub上:https://github.com/networkx/networkx
使用您的示例并添加一些额外的点,并将时间设置为权重:
import numpy as np
import matplotlib.pyplot as plt
G = nx.Graph()
map_dict = [
{'start': 'a', 'end': 'b', 'length': 5, 'time': 55},
{'start': 'a', 'end': 'c', 'length': 8, 'time': 125},
{'start': 'b', 'end': 'c', 'length': 22, 'time': 275},
{'start': 'c', 'end': 'd', 'length': 16, 'time': 210},
{'start': 'b', 'end': 'e', 'length': 22, 'time': 14},
{'start': 'd', 'end': 'e', 'length': 7, 'time': 6} ]
for pts in map_dict:
G.add_edge(pts['start'], pts['end'], weight=pts['time'])
path = nx.shortest_path(G, source='a',target='e')
print(path)
path_edges = zip(path, path[1:])
path_edges = set(path_edges)
pos = nx.spring_layout(G)
nx.draw(G, pos, node_color='lawngreen', with_labels = True)
nx.draw_networkx_nodes(G, pos, nodelist=path, node_color='mediumseagreen')
nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color='r', width=10)
plt.axis('equal')
plt.show()
输出结果:
['a', 'b', 'e']
![这里是图片描述](https://istack.dev59.com/PWVQk.webp)