C++ Boost

bellman_ford_shortest_paths

Graphs: directed or undirected
Properties: distance, weight
Complexity: O(V E)
Where Defined: boost/graph/bellman_ford_shortest_paths.hpp

(1)
template <class EdgeListGraph, class Size, class WeightMap, class DistanceMap>
bool bellman_ford_shortest_paths(EdgeListGraph& g, Size N, 
  WeightMap w, DistanceMap d)

(2)
template <class EdgeListGraph, class Size, class WeightMap, class DistanceMap,
          class BellmanFordVisitor>
bool bellman_ford_shortest_paths(EdgeListGraph& g, Size N, WeightMap w, 
  DistanceMap d, BellmanFordVisitor visit)

The Bellman-Ford algorithm [4,11,20,8] solves the single-source shortest paths problem for a graph with both positive and negative edge weights. See Section Shortest-Paths Algorithms for a description of the single-source shortest paths problem. If a cycle with negative length is detected, the algorithm returns false. The argument N should be the number of vertices in the graph. The source vertex is indicated by initializing the distance of the source vertex to zero and the distances of the rest of the vertices to std::numeric_limits<T>::max().

Requirements on Types

Complexity

The time complexity is O(V E).

Example

The source code for this example is in examples/bellman_ford.cpp.

  enum { u, v, x, y, z, N };
  char name[] = { 'u', 'v', 'x', 'y', 'z' };

  typedef std::pair<int,int> E;
  E edges[] = { E(u,y), E(u,x), E(u,v),
                E(v,u),
                E(x,y), E(x,v),
                E(y,v), E(y,z),
                E(z,u), E(z,x) };
  
  int weight[] = { -4, 8, 5,
                   -2,
                   9, -3,
                   7, 2,
                   6, 7 };

  typedef edge_list<E*,E,ptrdiff_t> Graph;
  Graph g(edges, edges + sizeof(edges)/sizeof(E));
    
  vector<int> distance(N,std::numeric_limits<short>::max());
  vector<int> parent(N,-1);
  
  distance[z] = 0;
  parent[z] = z;
  bool r = bellman_ford_shortest_paths(g, int(N), weight,
                                       distance.begin(),
                                       parent.begin());
  if (r)  
    for (int i = 0; i < N; ++i)
      std::cout << name[i] << ": " << distance[i]
                << " " << name[parent[i]] << std::endl;
  else
    std::cout << "negative cycle" << std::endl;
The distance and predecessor for each vertex is:
  u: 2 v
  v: 4 x
  x: 7 z
  y: -2 u
  z: 0 z


Copyright © 2000 Jeremy Siek, Univ.of Notre Dame (jsiek@lsc.nd.edu)