dijkstra in python
时间: 2023-09-16 18:15:05 浏览: 112
Python dijkstra算法.docx
Here's an implementation of Dijkstra's algorithm in Python:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
current_distance, current_node = heapq.heappop(pq)
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(pq, (distance, neighbor))
return distances
```
To use this function, you'll need to represent your graph as a dictionary of dictionaries. Each key in the outer dictionary represents a node in the graph, and its value is another dictionary that maps the node's neighbors to their edge weights. For example:
```python
graph = {
'A': {'B': 2, 'C': 1},
'B': {'A': 2, 'D': 4},
'C': {'A': 1, 'D': 3},
'D': {'B': 4, 'C': 3}
}
print(dijkstra(graph, 'A'))
# Output: {'A': 0, 'B': 2, 'C': 1, 'D': 4}
```
This code will find the shortest path from the start node ('A') to every other node in the graph. The output is a dictionary that maps each node to its shortest distance from the start node.
阅读全文