dijkstra算法python实现
时间: 2023-04-30 11:02:51 浏览: 80
Dijkstra算法.md
Dijkstra算法可以用来求最短路径。在Python中可以使用堆数据结构来实现。具体实现可以参考以下代码:
```python
import heapq
def dijkstra(graph, start):
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
priority_queue = [(0, start)]
while priority_queue:
current_distance, current_vertex = heapq.heappop(priority_queue)
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(priority_queue, (distance, neighbor))
return distances
```
在上述代码中,“graph”是邻接表表示的图,“start”是起点。算法会返回一个字典,表示每个顶点到起点的最短距离。
阅读全文