如何用python代码寻找最小路径
时间: 2024-05-08 19:19:17 浏览: 33
你可以使用 Dijkstra 算法来寻找最小路径,以下是 Python 代码示例:
```
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
(distance, current_node) = heapq.heappop(pq)
if distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance_to_neighbor = distance + weight
if distance_to_neighbor < distances[neighbor]:
distances[neighbor] = distance_to_neighbor
heapq.heappush(pq, (distance_to_neighbor, neighbor))
return distances
# 例:图的邻接表表示法
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}
}
# 从 A 出发,寻找每个节点的最短距离
print(dijkstra(graph, 'A'))
```
这段代码可以在给定的图上使用 Dijkstra 算法寻找从指定起点(这里为 'A')到其它每个节点的最短路径。
阅读全文