rilpoint_mw113


Bellman-Ford算法

Bellman-Ford算法是求解单源最短路径问题的一种算法。单源点的最短路径问题是指:给定一个加权有向图G和源点s,对于图G中的任意一点v,求从s到v的最短路径。

Bellman-Ford算法伪代码如下:

BF(G,w,s) // G = Graph, w = weight, s=source
Determine Single Source(G,s);
set Distance(s) = 0; Predecessor(s) = nil;
for each vertex v in G other than s, 
   set Distance(v) = infinity, Predecessor(v) = nil;
for i <- 1 to |V(G)| - 1 do   //|V(G)| Number of vertices in the graph
   for each edge (u,v) in G do
      if Distance(v) > Distance(u) + w(u,v) then
         set Distance(v) = Distance(u) + w(u,v), Predecessor(v) = u;  
for each edge (u,r) in G do
   if Distance(r) > Distance(u) + w(u,r);
      return false; //This means that the graph contains a cycle of negative weight 
                    //and the shortest paths are not well defined
return true; //Lengths of shortest paths are in Distance array