迪杰斯特拉算法是一种用于解决带权有向图中单源最短路径问题的算法。该算法由荷兰计算机科学家艾兹格·迪杰斯特拉于1956年提出。它通过逐步迭代,找到从源节点到其他所有节点的最短路径。
import heapq
def dijkstra(graph, start):
# 初始化距离字典和已访问节点集合
distances = {node: float('infinity') for node in graph}
distances[start] = 0
visited = set()
# 使用最小堆来存储待访问节点及其距离
pq = [(0, start)]
while pq:
# 弹出距离最小的节点
current_distance, current_node = heapq.heappop(pq)
# 如果节点已访问,则跳过
if current_node in visited:
continue
visited.add(current_node)
# 更新邻居节点的距离
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。