dijkstra算法代码phyth

Dijkstra算法是一种用于解决单源最短路径问题的算法。在Python中,可以使用以下代码实现Dijkstra算法:

import heapq

def dijkstra(graph, start):
# 初始化距离字典,将所有节点的距离设置为无穷大
distances = {node: float(‘inf’) for node in graph}
# 将起点的距离设置为0
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’: 1, ‘C’: 3}, ‘B’: {‘A’: 1, ‘C’: 2}, ‘C’: {‘A’: 3, ‘B’: 2}},从A到B的距离是1,从A到C的距离是3,从B到A的距离是1,从B到C的距离是2,从C到A的距离是3,从C到B的距离是2。下篇我们谈谈matlab的实现

你可能感兴趣的:(python)