用python实现Dijkstra点到点最短路径可视化的代码
时间: 2023-06-05 13:04:06 浏览: 205
感谢您的提问!以下是Python实现Dijkstra算法求点到点最短路径并可视化的代码,希望能够帮到您:
```python
import heapq
import networkx as nx
import matplotlib.pyplot as plt
def dijkstra(graph, start, end):
# 初始化距离字典和前驱节点字典
dist = {start: 0}
prev = {start: None}
# 使用堆来优化Dijkstra算法的查找过程
pq = [(0, start)]
while pq:
(d, u) = heapq.heappop(pq)
# 如果当前节点已经被访问过,则直接跳过
if u in dist and d > dist[u]:
continue
# 遍历所有的邻居节点,更新距离和前驱节点
for v, w in graph[u].items():
if v not in dist or d + w < dist[v]:
dist[v] = d + w
prev[v] = u
heapq.heappush(pq, (dist[v], v))
path = []
# 根据前驱节点字典来重构路径
while end:
path.append(end)
end = prev[end]
# 路径反转后返回
return path[::-1]
if __name__ == '__main__':
# 构建有向图
G = nx.DiGraph()
G.add_nodes_from(['A', 'B', 'C', 'D', 'E', 'F'])
G.add_weighted_edges_from([('A', 'B', 6), ('A', 'D', 1),
('B', 'D', 2), ('B', 'E', 2),
('B', 'C', 5), ('C', 'E', 5),
('C', 'F', 2), ('D', 'E', 1),
('E', 'F', 4)])
pos = nx.spring_layout(G)
# 调用Dijkstra算法求最短路径
path = dijkstra(nx.to_dict_of_dicts(G), 'A', 'F')
# 绘制有向图和最短路径
nx.draw_networkx_edge_labels(G, pos, edge_labels={(u, v): w['weight'] for u, v, w in G.edges(data=True)})
nx.draw(G, pos, with_labels=True)
nx.draw_networkx_nodes(G, pos, nodelist=path, node_color='r')
plt.show()
```
在这段代码中,我们首先定义了一个`dijkstra`函数,用于实现Dijkstra算法的核心部分。然后我们构建了一个有向图`G`,并将其转换为字典格式,然后传入`dijkstra`函数中,调用该函数求取A到F的最短路径。最后使用`matplotlib`库绘制出该有向图和最短路径。
阅读全文