用优先队列实现dijkstra算法
时间: 2023-05-18 18:06:01 浏览: 112
可以使用以下代码实现:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
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是一个字典,表示图的邻接表,start是起点。这段代码使用了优先队列来实现dijkstra算法,可以在O(E log V)的时间内求出从起点到其它所有点的最短距离。
阅读全文