如何在Python中实现Bellman-Ford算法,并考虑图中存在负权重边的情况?请提供示例代码。
时间: 2024-11-26 09:32:46 浏览: 8
Bellman-Ford算法是解决单源最短路径问题的经典算法之一,特别是对于包含负权重边的图。在Python中实现Bellman-Ford算法需要考虑到边的权重可能为负值,并且算法需要能够检测图中是否存在负权重环。下面是一个简化的示例代码,用于说明如何在Python中实现Bellman-Ford算法:
参考资源链接:[Python图算法对比:Bellman-Ford与Dijkstra最短路径解析](https://wenku.csdn.net/doc/pkm7gcz9zf?spm=1055.2569.3001.10343)
```python
def bellman_ford(graph, source):
# 初始化距离表,所有顶点距离源点无穷大
distance = {node: float('inf') for node in graph}
distance[source] = 0
# 松弛所有边 |V| - 1次
for _ in range(len(graph) - 1):
for node in graph:
for neighbour, weight in graph[node].items():
if distance[node] + weight < distance[neighbour]:
distance[neighbour] = distance[node] + weight
# 检测负权重环
for node in graph:
for neighbour, weight in graph[node].items():
if distance[node] + weight < distance[neighbour]:
print(
参考资源链接:[Python图算法对比:Bellman-Ford与Dijkstra最短路径解析](https://wenku.csdn.net/doc/pkm7gcz9zf?spm=1055.2569.3001.10343)
阅读全文