单源最短路径算法代码python
时间: 2023-10-13 22:08:06 浏览: 44
单源最短路径算法有多种,其中比较常用的是Dijkstra算法和Bellman-Ford算法。下面是它们的Python代码实现:
Dijkstra算法:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
(dist, node) = heapq.heappop(pq)
if dist > distances[node]:
continue
for neighbor, weight in graph[node].items():
distance = dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
```
Bellman-Ford算法:
```python
def bellman_ford(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
for _ in range(len(graph) - 1):
for node in graph:
for neighbor, weight in graph[node].items():
if distances[node] + weight < distances[neighbor]:
distances[neighbor] = distances[node] + weight
return distances
```
其中,graph是一个字典,表示图的邻接表。例如,对于以下有向加权图:
```
A -> B (1)
A -> C (4)
B -> C (2)
B -> D (5)
C -> D (1)
```
可以表示为如下的邻接表:
```python
graph = {
'A': {'B': 1, 'C': 4},
'B': {'C': 2, 'D': 5},
'C': {'D': 1},
'D': {}
}
```