DIJKSTRA最短路径路由python代码
时间: 2023-10-13 07:27:04 浏览: 78
以下是一个简单的 Python 实现 Dijkstra 算法的代码:
```python
import heapq
def dijkstra(graph, start):
"""
计算从 start 到其他节点的最短路径
graph: 字典类型,key 为节点名称,value 为连接的节点和距离的字典
start: 起始节点名称
"""
distances = {} # 存储从 start 到各个节点的最短距离
for node in graph:
distances[node] = float('inf')
distances[start] = 0
pq = [(0, start)]
while pq:
(dist, current_node) = heapq.heappop(pq)
if dist > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
# 测试
graph = {
'A': {'B': 2, 'C': 5},
'B': {'A': 2, 'C': 1},
'C': {'A': 5, 'B': 1, 'D': 3},
'D': {'C': 3}
}
print(dijkstra(graph, 'A')) # 输出 {'A': 0, 'B': 2, 'C': 3, 'D': 6}
```
注:以上代码中,使用 heapq 模块实现了一个优先队列,用于存储节点及其到起始节点的距离。
阅读全文