题目:
对于有向带权图G=(V,E),其中每条边的权值都是非负实数。给定V中的一个节点(称为源点),计算源点到其他节点的最短路径,即单源最短路径。
# 引入堆
import heapq
# 迪杰斯特拉函数
# graph各点之间的距离
# start源点
def dijkstra(graph, start):
# 初始化距离字典,存储源点到各个节点的距离
distance = {node: float('inf') for node in graph}
# print(distance)
# 源点到自身的距离为0
distance[start] = 0
# 使用优先队列来存储节点和对应的距离
queue = [(0, start)]
while queue:
# 从优先队列中弹出一个元组,元组的第一个元素是当前节点到起始节点的距离,第二个元素是当前节点的名称。
current_distance, current_node = heapq.heappop(queue)
# 如果当前距离大于已计算的距离,则忽略
if current_distance > distance[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance_to_neighbor = current_distance + weight
# 如果通过当前节点到达邻居节点的距禽小于已计算的距离
if distance_to_neighbor < distance[neighbor]:
distance[neighbor] = distance_to_neighbor
heapq.heappush(queue, (distance_to_neighbor, neighbor))
return distance
# 用字典表示各点之间的距离
graph = {
'1': {'2': 2, '3': 5},
'2': {'3': 2, '4': 6},
'3': {'4': 7, '5': 1},
'4': {'3': 2, '5': 4},
'5': {}
}
# 源点为A
start_node = '1'
# 调用迪杰斯特拉函数,返回源点到各点的最短路径
result = dijkstra(graph, start_node)
print("源点到各点的最短路径为", result)