Bellman-Ford算法代码
时间: 2024-01-16 20:05:43 浏览: 111
bellman ford 算法
3星 · 编辑精心推荐
下面是Bellman-Ford算法的Python代码:
```python
def bellman_ford(graph, start_node):
# 初始化距离为无穷大
distance = {node: float('inf') for node in graph}
# 起始节点距离为0
distance[start_node] = 0
# 遍历所有节点,最多进行n-1次
for _ in range(len(graph) - 1):
# 遍历所有边,更新距离
for node in graph:
for neighbor in graph[node]:
new_distance = distance[node] + graph[node][neighbor]
if new_distance < distance[neighbor]:
distance[neighbor] = new_distance
# 检查是否存在负权环
for node in graph:
for neighbor in graph[node]:
if distance[node] + graph[node][neighbor] < distance[neighbor]:
raise ValueError("存在负权环")
return distance
```
其中,graph是一个字典,表示图的邻接表。start_node是起始节点的名称,distance是一个字典,表示每个节点到起始节点的最短距离。如果存在负权环,则抛出ValueError异常。
阅读全文