用python语言写一段通用的Dijkstra算法,并标注每一行的注释
时间: 2024-05-20 18:18:18 浏览: 82
Python语言编写的Dijkstra算法
# 初始化一个无穷大的数
INF = float('inf')
# 定义Dijkstra算法函数
def dijkstra(graph, start):
# 初始化距离字典
dist = {node: INF for node in graph}
# 起点到起点的距离为0
dist[start] = 0
# 初始化已访问集合
visited = set()
# 循环直到所有节点都被访问
while len(visited) != len(graph):
# 找到未访问节点中距离起点最近的节点
current_node = min((set(dist.keys()) - visited), key=dist.get)
# 将该节点标记为已访问
visited.add(current_node)
# 更新与当前节点相邻的节点的距离
for neighbor_node, distance in graph[current_node].items():
if neighbor_node not in visited:
new_distance = dist[current_node] + distance
if new_distance < dist[neighbor_node]:
dist[neighbor_node] = new_distance
# 返回最短路径字典
return dist
# 测试Dijkstra算法
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
start_node = 'A'
shortest_distances = dijkstra(graph, start_node)
print(shortest_distances)
阅读全文