用python语言写一段dijkstra算法的代码
时间: 2023-12-17 09:46:35 浏览: 54
Python语言编写的Dijkstra算法
以下是使用Python语言实现Dijkstra算法的示例代码:
```python
import heapq
def dijkstra(graph, source):
# 初始化距离字典,距离为正无穷大
distances = {node: float('inf') for node in graph}
# 设置源节点的距离为0
distances[source] = 0
# 初始化优先队列
pq = [(0, source)]
# 开始遍历
while pq:
# 取出优先队列中距离最小的节点
(curr_dist, curr_node) = heapq.heappop(pq)
# 如果当前节点的距离已经比之前记录的距离还要长,跳过
if curr_dist > distances[curr_node]:
continue
# 遍历当前节点的所有邻居
for neighbor, weight in graph[curr_node].items():
# 计算从源节点到邻居节点的距离
distance = curr_dist + weight
# 如果计算出的距离比之前记录的距离更短,则更新距离字典和优先队列
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
# 返回距离字典
return distances
# 测试
graph = {
'A': {'B': 5, 'C': 1},
'B': {'A': 5, 'C': 2, 'D': 1},
'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8},
'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6},
'E': {'C': 8, 'D': 3},
'F': {'D': 6}
}
print(dijkstra(graph, 'A'))
```
输出结果为:
```
{'A': 0, 'B': 3, 'C': 1, 'D': 4, 'E': 7, 'F': 10}
```
这表示从源节点A到其他节点的最短距离分别为0、3、1、4、7、10。
阅读全文