写出Dijkstra算法的代码
时间: 2024-11-03 07:08:34 浏览: 16
Dijkstra算法是一种用于寻找图中两点之间最短路径的贪心算法,通常应用于有向无环图(DAG)或加权图。以下是Python版本的Dijkstra算法实现:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典,所有节点的距离设为无穷大,起点距离设为0
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': 3},
'C': {'A': 1, 'D': 4},
'D': {'B': 3, 'C': 4, 'E': 2},
'E': {'D': 2}
}
start_node = 'A'
shortest_distances = dijkstra(graph, start_node)
阅读全文