学习笔记仅供参考......(希望对各位有帮助)

简单回顾一下
这里我就直接上代码,先过一遍代码
import heapq
MAX = float('inf')
def dijkstra(graph_matrix, start):
# 图的顶点数
num_vertices = len(graph_matrix)
# 初始化距离列表,用于记录每个顶点到起始顶点的距离
distances = [float('infinity')] * num_vertices
#最开始自己和自己的距离当然为0啦
distances[start] = 0
# 使用优先队列(堆)来选择距离最短的顶点
pq = [(0, start)]
while pq:
# 从堆中取出距离最短的顶点(用的是优先队列性质)
current_distance, current_vertex = heapq.heappop(pq)
# 如果当前距离大于当前顶点到起始顶点的距离,则跳过
if current_distance > distances[current_vertex]:
continue
# 遍历当前顶点的相邻顶点
for neighbor in range(num_vertices):
# 如果有连接到相邻顶点的边,并且通过当前顶点到达相邻顶点的距离更短,则更新距离
if graph_matrix[current_vertex][neighbor] != 0:
distance = current_distance + graph_matrix[current_vertex][neighbor]
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
# 示例二维列表表示的图
graph_matrix = [
[0, 10, MAX, 4, MAX, MAX],
[10, 0, 8, 2, 6, MAX],
[MAX, 8, 10, 15, 1, 5],
[4, 2, 15, 0, 6, MAX],
[MAX, 6, 1, 6, 0, 12],
[MAX, MAX, 5, MAX, 12, 0]
]
start_vertex = 0 # 从顶点0开始
distances = dijkstra(graph_matrix, start_vertex)
print("从顶点 {} 到其他顶点的最短距离:".format(start_vertex))
for vertex, distance in enumerate(distances):
print("到顶点 {} 的最短距离为 {}".format(vertex, distance))
# [0, 6, 11, 4, 10, 16]
</

本文介绍了如何使用Dijkstra算法求解城市紧急救援问题,通过Python实现,包括构建邻接表、初始化数据结构、优先队列操作和计算最短路径。代码实例展示了从给定起点到终点的救援队调度和路径寻找过程。
最低0.47元/天 解锁文章
884





