Floyd's All Pairs Shortest Path Algorithm

Environment: C++, any version


Graph algorithms work on nodes and edges. Nodes and edges are represented in many ways. This well-known algorithm uses a connectivity matrix. The matrix is a square matrix with number of columns and rows same as many as there are Nodes. The diagonal elements are set to zero. The offdiagonals are 1 if connected 0 if not connected. (You could also use distances if you are dealing with something like road distances.) This matrix is modified to make the cost of the disconnected nodes to infinity. You can make slight modifications so that the inputs take STL vector< vector<int> > as a matrix data structure. You could drop the lower half of the matrix; you can also consider using the upper half for the original data and using the lower half for the distance matrix and save entirely on an extra copy of the matrix.

Since the earlier version, I have added code that stores the nodes in the path in addition to the length, so that the actual paths are also computed in addition to the path lengths, thus doing what Djikstra's algorithm was primarily meant to do, as well.

The output of the algorithm is a matrix of the shortest distances between every pair of points and a comma-separated list of nodes representing the paths.

- L. Shyamal
Bangalore, India

The Code

#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;

// Floyd's All pairs shortest path algorithm (O (n^3) )
// input is adjacency matrix output is matrix of shortest paths
// C is the adjacency matrix
// n is the order of the square matrix
// A is the all pairs shortest paths matrix
// we assume that A is allocated by the caller
int ComputeFloydAPSP(int *C, int n, int *A, string* s)

  int i,j,k;

  // set all connected positions to 1
  // and all unconnected positions to infinity
  for (i=0; i<n; i++)
    for (j=0; j<n; j++)
      if ( *(C+i*n+j) == 0)
        *(A+i*n+j) = 999999999;    // Does this look like infinity?
        *(A+i*n+j) = 1;
        char sz[3]="";

  // set the diagonals to zero
  for (i=0; i<n; i++)
    *(A+i*n+i) = 0;

  // for each route via k from i to j pick any better routes and
  // replace A[i][j] path with sum of paths i-k and j-k
  for (k=0; k<n; k++)
    for (i=0; i<n; i++)
      for (j=0; j<n; j++)
        if ( *(A+i*n+k) + *(A+k*n+j) < *(A+i*n+j) )
          // A[i][j] = A[i][k] + A[k][j];
          *(A+i*n+j) = *(A+i*n+k)+ *(A+k*n+j);

  return 0;
}    // Floyd's algorithm

// this is for testing Floyd's algorithm
// demonstrates the allocation and 
// deallocation of memory for the matrices
void FloydTest()

  // allocate the entire matrix in one linear array
  // trying to allocate it as an array of pointers to arrays
  // didn't quite work, possibly because the [] and * notation
  // aren't quite replaceable
  int n=10;
  int *C=new int[n*n];

  C[0 ]=0;C[1 ]=1;C[2 ]=0;C[3 ]=0;C[4 ]=0;C[5 ]=0;C[6 ]=0;C[7 ]=0;
          C[8 ]=0;C[9 ]=0;

  int* A = new int[n*n];
  string* s = new string[n*n];
  printf("Initial matrix\n");
  for(int i=0;i<n;i++)
    for(int j=0;j<n;j++)
      printf("%d ",*(C+i*n+j));

  ComputeFloydAPSP (C,n,A,s);

  printf("Final shortest distances\n");
    for(int j=0;j<n;j++)
      printf("%d ",*(A+i*n+j));
  printf("End of All pairs Shortest paths\n");
    for(int j=i+1;j<n;j++)
      printf("path from %d to %d is %s\n",i+1,j+1,s[i*n+j].c_str());

    delete [] A;
    delete [] C;
    delete [] s;

}    // end of FloydTest

void main()
  char c;


  • There is a problem!!

    Posted by yg_sun on 02/04/2005 07:24am

    for (k=0; k Reply

  • link to Dijkstra

    Posted by Legacy on 01/21/2004 12:00am

    Originally posted by: Dijkstrafan

    The correct link to Dijkstra's memorial site is

  • good illustration of logic

    Posted by Legacy on 12/08/2003 12:00am

    Originally posted by: satish kumar

    it is a good illustration of the topic.

  • Floyd's All Pairs Shortest Path Algorithm

    Posted by Legacy on 04/30/2003 12:00am

    Originally posted by: Debi Prasanna Patnaik

    Works nice ...

  • And in VB have a a problems?

    Posted by Legacy on 11/17/2002 12:00am

    Originally posted by: Cesar Sandoval

    i dont know i recently see the post but i need know if is same in VB NET or i ll have a prblems with implementation


  • Nice try

    Posted by Legacy on 06/24/2002 12:00am

    Originally posted by: yoav

    Nice try to implements.
    look very good.
    Maybe have some problems in implemeting ,but good try

  • infinity

    Posted by Legacy on 06/16/2002 12:00am

    Originally posted by: Dominator


    >> 999999999; // does this look like infinity ?

    Well, it looks like infinity, bot it is not, and quite easily happen that a path is longer than the value above.

    One solution:

    *(A+i*n+j) = (unsigned int)(-1);

    which gives the variable the greatest possible value of type "int".

    Other solution:

    #include <limits.h>

    *(A+i*n+j) = INT_MAX;

    - or -

    *(A+i*n+j) = LONG_LONG_MAX;

    depending on which type of values you are working with. Here, in your code, INT_MAX is acceptable since A is declared as "int *". For an Alpha processor, LONG_LONG_MAX is the greates possible value, and it is 64 bit long.
    "limits.h" is a part of ANSI Standard C and can be found in the "include" directory.

    Have a nice day,

  • No Comments

    Posted by Legacy on 06/06/2002 12:00am

    Originally posted by: RINAT

    No Comments

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Hurricane Sandy was one of the most destructive natural disasters that the United States has ever experienced. Read this success story to learn how Datto protected its partners and their customers with proactive business continuity planning, heroic employee efforts, and the right mix of technology and support. With storm surges over 12 feet, winds that exceeded 90 mph, and a diameter spanning more than 900 miles, Sandy resulted in power outages to approximately 7.5 million people, and caused an estimated $50 …

  • The impact of a data loss event can be significant. Real-time data is essential to remaining competitive. Many companies can no longer afford to rely on a truck arriving each day to take backup tapes offsite. For most companies, a cloud backup and recovery solution will eliminate, or significantly reduce, IT resources related to the mundane task of backup and allow your resources to be redeployed to more strategic projects. The cloud - can now be comfortable for you – with 100% recovery from anywhere all …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds