迪克斯特拉算法python
时间: 2023-07-10 14:10:22 浏览: 92
python实现狄克斯特拉算法
好的,迪杰斯特拉算法(Dijkstra's algorithm)是一种用于求解加权图中单源最短路径的算法。以下是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`是一个字典,表示加权图的邻接表。键为顶点,值为一个字典,表示该顶点的邻居顶点和边权重。`start`表示起始顶点。函数返回一个字典,表示从起始顶点到其他顶点的最短距离。
阅读全文