迪杰斯特拉算法代码模板
时间: 2024-12-18 13:13:21 浏览: 31
迪杰斯特拉(Dijkstra's Algorithm)是一种用于寻找图中两个节点之间最短路径的经典算法,它通常用于解决单源最短路径问题。以下是迪杰斯特拉算法的基本Python代码模板:
```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
# 示例用法:
graph = {
'A': {'B': 5, 'C': 1},
'B': {'A': 5, 'D': 2},
'C': {'A': 1, 'D': 4},
'D': {'B': 2, 'C': 4, 'E': 8},
'E': {'D': 8}
}
start_node = 'A'
shortest_distances = dijkstra(graph, start_node)
print("Shortest distances from {}:".format(start_node))
for node, dist in shortest_distances.items():
print(f"{node}: {dist} steps")
阅读全文