dijkstra用python实现
时间: 2023-09-21 13:06:54 浏览: 39
Sure, Dijkstra's algorithm can be easily implemented in Python. Here's some sample code:
```
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
```
This implementation uses a priority queue to keep track of the nodes to visit next, and updates the distance to each node as it traverses the graph. Hope this helps!