dijkstra标号法python
时间: 2023-11-09 10:01:09 浏览: 87
Dijkstra算法是一种用于解决带权图的单源最短路径问题的贪心算法。其中标号法是一种实现Dijkstra算法的方法之一,下面是一个使用Python实现Dijkstra标号法的示例代码:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典和堆
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
heap = [(0, start)]
while heap:
# 弹出堆中距离最小的节点
current_distance, current_vertex = heapq.heappop(heap)
# 如果当前节点已经被处理过,则跳过
if current_distance > distances[current_vertex]:
continue
# 遍历当前节点的邻居节点
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
# 如果新的距离比原来的距离更短,则更新距离字典和堆
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(heap, (distance, neighbor))
return distances
# 示例图
graph = {
'A': {'B': 1, 'C': 4},
'B': {'D': 3},
'C': {'D': 2},
'D': {'E': 1},
'E': {}
}
# 计算从节点A出发到其他节点的最短距离
distances = dijkstra(graph, 'A')
print(distances)
# 输出:{'A': 0, 'B': 1, 'C': 4, 'D': 4, 'E': 5}
```
阅读全文