遍历所有点的最短路径python
时间: 2023-08-07 16:42:15 浏览: 110
可以使用Dijkstra算法来遍历所有点的最短路径,以下是Python实现的示例代码:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典和堆
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
heap = [(0, start)]
while heap:
# 取出堆中距离最小的节点
current_distance, current_vertex = heapq.heappop(heap)
# 如果当前节点已经被处理过,则跳过
if current_distance > distances[current_vertex]:
continue
# 处理当前节点的邻居节点
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
# 如果发现更短的路径,则更新距离字典和堆
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(heap, (distance, neighbor))
return distances
# 示例代码
graph = {
'A': {'B': 1, 'C': 4},
'B': {'D': 3},
'C': {'D': 2},
'D': {'E': 1},
'E': {}
}
distances = dijkstra(graph, 'A')
print(distances) # {'A': 0, 'B': 1, 'C': 4, 'D': 4, 'E': 5}
```
以上代码实现了对图中所有点的最短路径遍历,并输出了距离起点的距离字典。你可以根据自己的需求进行修改。
阅读全文