python实现迪杰斯特拉算法,并打印最短距离和途径节点
时间: 2024-10-08 07:01:05 浏览: 27
Python实现迪杰斯特拉算法并生成最短路径的示例代码
在Python中,你可以使用字典(dict)来实现Dijkstra算法,这是一个用于寻找图中两点之间最短路径的经典算法。这里是一个简单的版本:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('infinity') for node in graph}
distances[start] = 0
queue = [(0, start)]
while queue:
current_distance, current_node = heapq.heappop(queue)
if current_distance > distances[current_node]:
continue # 如果当前距离已经更新过,跳过本次循环
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(queue, (distance, neighbor))
return distances, [current_node for current_distance, current_node in sorted(distances.items())]
# 使用示例:
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'D': 5},
'C': {'A': 4, 'E': 8},
'D': {'B': 5, 'E': 11},
'E': {'C': 8, 'D': 11}
}
shortest_distances, path = dijkstra(graph, 'A')
print(f"Shortest Distance to each node from A: {shortest_distances}")
print(f"Path: {path[::-1]}") # 注意路径是从终点反向的
阅读全文