蓝桥杯最短路python
时间: 2023-11-12 19:59:07 浏览: 47
蓝桥杯最短路python的解法有很多种,其中比较常用的是Dijkstra算法和Floyd算法。Dijkstra算法适用于单源最短路问题,而Floyd算法适用于多源最短路问题。
下面是Dijkstra算法的Python代码实现:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
(dist, current_node) = heapq.heappop(pq)
if dist > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
```
其中,graph是一个字典,表示图的邻接表;start是起点。