📜  Bellman-Ford算法

📅  最后修改于: 2020-12-10 07:00:27             🧑  作者: Mango

Bellman-Ford算法

解决单个最短路径问题,其中边权重可能为负,但不存在负循环。

当有向图G的某些边缘可能具有负权重时,此算法正确运行。当没有负重量的循环时,我们可以找出源与目标之间的最短路径。

它比Dijkstra的算法慢,但功能更多,因为它能够处理一些负重量边缘。

该算法检测图中的负循环并报告其存在。

基于“松弛原理”,其中更精确的值逐渐将近似值恢复到适当的距离,直到最终达到最佳解。

给定具有源s和权重函数w:E→R的加权有向图G =(V,E),Bellman-Ford算法返回一个布尔值,该布尔值指示是否有可从源获得的负权重周期。如果存在这样的循环,该算法将产生最短的路径及其权重。当且仅当图形不包含负数(可从源到达的权重循环)时,算法才返回TRUE。

递归关系

dist k [u] = [min [dist k-1 [u],min [dist k-1 [i] + cost [i,u]]]],除u外,i等于i。

k→k是源顶点
u→u是目标顶点
i→关于顶点的待扫描边缘数。< p="">

示例:首先,我们列出所有边缘及其权重。

解:

dist k [u] = [min [dist k-1 [u],min [dist k-1 [i] + cost [i,u]]]],因为i≠u。

dist 2 [2] = min [dist 1 [2],min [dist 1 [1] + cost [1,2],dist 1 [3] + cost [3,2],dist 1 [4] + cost [ 4,2],dist 1 [5] + cost [5,2]]]

最小值= [6,0 + 6,5 +(-2),∞+∞,∞+∞] = 3

dist 2 [3] = min [dist 1 [3],min [dist 1 [1] + cost [1,3],dist 1 [2] + cost [2,3],dist 1 [4] + cost [ 4,3],dist 1 [5] + cost [5,3]]]

最小值= [5,0 +∞,6 +∞,∞+∞,∞+∞] = 5

dist 2 [4] = min [dist 1 [4],min [dist 1 [1] + cost [1,4],dist 1 [2] + cost [2,4],dist 1 [3] + cost [ 3,4],dist 1 [5] + cost [5,4]]]

dist 2 [5] = min [dist 1 [5],min [dist 1 [1] + cost [1,5],dist 1 [2] + cost [2,5],dist 1 [3] + cost [ 3,5],dist 1 [4] + cost [4,5]]]

最小值= [∞,0 +∞,6 +∞,5 + 3,∞+ 3] = 8

dist 3 [2] = min [dist 2 [2],min [dist 2 [1] + cost [1,2],dist 2 [3] + cost [3,2],dist 2 [4] + cost [ 4,2],dist 2 [5] + cost [5,2]]]

最小值= [3,0 + 6,5 +(-2),5 +∞,8 +∞] = 3

dist 3 [3] = min [dist 2 [3],min [dist 2 [1] + cost [1,3],dist 2 [2] + cost [2,3],dist 2 [4] + cost [ 4,3],dist 2 [5] + cost [5,3]]]

最小值= [5,0 +∞,3 +∞,5 +∞,8 +∞] = 5

dist 3 [4] = min [dist 2 [4],min [dist 2 [1] + cost [1,4],dist 2 [2] + cost [2,4],dist 2 [3] + cost [ 3,4],dist 2 [5] + cost [5,4]]]

最小值= [5,0 +∞,3 +(-1),5 + 4,8 +∞] = 2

dist 3 [5] = min [dist 2 [5],min [dist 2 [1] + cost [1,5],dist 2 [2] + cost [2,5],dist 2 [3] + cost [ 3,5],dist 2 [4] + cost [4,5]]]

最小值= [8,0 +∞,3 +∞,5 + 3,5 + 3] = 8

dist 4 [2] = min [dist 3 [2],min [dist 3 [1] + cost [1,2],dist 3 [3] + cost [3,2],dist 3 [4] + cost [ 4,2],dist 3 [5] + cost [5,2]]]

最小值= [3,0 + 6,5 +(-2),2 +∞,8 +∞] = 3

dist 4 [3] = min [dist 3 [3],min [dist 3 [1] + cost [1,3],dist 3 [2] + cost [2,3],dist 3 [4] + cost [ 4,3],dist 3 [5] + cost [5,3]]]

最小值= 5,0 +∞,3 +∞,2 +∞,8 +∞] = 5

dist 4 [4] = min [dist 3 [4],min [dist 3 [1] + cost [1,4],dist 3 [2] + cost [2,4],dist 3 [3] + cost [ 3,4],dist 3 [5] + cost [5,4]]]

最小值= [2,0 +∞,3 +(-1),5 + 4,4,8 +∞] = 2

dist 4 [5] = min [dist 3 [5],min [dist 3 [1] + cost [1,5],dist 3 [2] + cost [2,5],dist 3 [3] + cost [ 3,5],dist 3 [5] + cost [4,5]]]

最小值= [8,0 +∞,3 +∞,8,5] = 5


u→u是目标顶点
i→关于顶点的待扫描边缘数。<>