Algorithmic Solutions > LEDA > LEDA Guide > Graph Algorithms > Shortest Path Algorithms > All Pairs Shortest Paths Algorithms > Example ALL_PAIRS_SHORTEST_PATHS()

Example of How to Use ALL_PAIRS_SHORTEST_PATHS()

The following program shows how the function ALL_PAIRS_SHORTEST_PATHS()can be used to compute the lengths of the shortest paths between all pairs of nodes in a directed graph. Edge costs may be positive or negative.

Remark: The graph algorithms in LEDA are generic, that is, they accept graphs as well as parameterized graphs.

In main() we first create a simple graph G with four nodes and five edges.

The costs of the edges are stored in the edge_array<int> cost. We use int as the number type for the edge costs. The variant of ALL_PAIRS_SHORTEST_PATHS() for double can be used in exactly the same way. You only need to replace int by double in the definition of cost and dist.

#include <LEDA/graph/graph.h>
#include <LEDA/graph/shortest_path.h>

using namespace leda;

int main()
{
  graph G; 

  node n0=G.new_node(); node n1=G.new_node();
  node n2=G.new_node(); node n3=G.new_node();

  edge e0=G.new_edge(n0,n1); edge e1=G.new_edge(n0,n3);
  edge e2=G.new_edge(n1,n2); edge e3=G.new_edge(n2,n3);
  edge e4=G.new_edge(n3,n1);
 
  edge_array<int> cost(G);
  cost[e0]=1; cost[e1]=-1; cost[e2]=-1;
  cost[e3]=2; cost[e4]=1;

The node_matrix<int> dist for G is used for the result of ALL_PAIRS_SHORTEST_PATHS(). dist(v,w) will contain the length of a shortest path from v to w if there are no negative cycles in G.

  
  node_matrix<int> dist(G);
  bool no_negative_cycle=ALL_PAIRS_SHORTEST_PATHS_T(G,cost,dist);
 
  if (no_negative_cycle) {
    node v;
    forall_nodes(v,G) {
      node w;
      forall_nodes(w,G) {
        if (v!=w) {
          std::cout << "The distance from "; G.print_node(v);
          std::cout << " to "; G.print_node(w);
          std::cout << " is " << dist(v,w) << std::endl;
        }
      }
    }
  }

  else std::cout << "There are negative cycles!" << std::endl
                 << "All dist-values unspecified!" << std::endl;

  return 0;
} 

See also:

All Pairs Shortest Paths Algorithms

Graphs

Parameterized Graphs

Edge Arrays

Two-Dimensional Node Arrays (node_matrix)


Graphs and Related Data Types


Manual Entries:

Manual Page Shortest Path Algorithms




Please send any suggestions, comments or questions to leda@algorithmic-solutions.com
© Copyright 2001-2003, Algorithmic Solutions Software GmbH