写一段代码使用Dijkstra算法找从一个城市到另一个城市的最短路径
时间: 2024-05-04 13:19:10 浏览: 90
以下是使用Dijkstra算法找从一个城市到另一个城市的最短路径的Python代码示例:
```python
import heapq
def dijkstra(graph, start, end):
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
current_distance, current_vertex = heapq.heappop(pq)
if current_vertex == end:
return distances[end]
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(pq, (distance, neighbor))
# 示例数据
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1, 'E': 3},
'E': {'D': 3}
}
start = 'A'
end = 'E'
shortest_distance = dijkstra(graph, start, end)
print(f'The shortest distance from {start} to {end} is {shortest_distance}')
```
在这个示例中,我们定义了一个名为`dijkstra`的函数,它接受三个参数:一个表示图的字典、起始点和目标点。函数使用堆优化的Dijkstra算法来计算最短路径。我们还定义了一个示例数据`graph`,它是一个包含五个节点的图。最后,我们调用`dijkstra`函数并输出结果。
阅读全文