python求最短路径
时间: 2023-11-04 17:22:05 浏览: 58
在Python中,可以使用Dijkstra算法或A*算法来求解最短路径。
下面是使用Dijkstra算法求解最短路径的示例代码:
```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 = {
'A': {'B': 5, 'C': 1},
'B': {'A': 5, 'C': 2, 'D': 1},
'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8},
'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6},
'E': {'C': 8, 'D': 3},
'F': {'D': 6}
}
print(dijkstra(graph, 'A'))
# 输出:{'A': 0, 'B': 3, 'C': 1, 'D': 4, 'E': 7, 'F': 10}
```
上述代码中,`graph`表示图的邻接矩阵,`start`表示起点。`dijkstra`函数返回一个字典,其中key为节点名,value为起点到该节点的最短距离。
另外,如果你需要使用A*算法求解最短路径,可以参考以下第三方库:
- NetworkX:https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.astar.astar_path.html
- Pathfinding:https://pypi.org/project/pathfinding/
阅读全文