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

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

  • Live Event Date: December 18, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this upcoming webcast …

Most Popular Programming Stories

More for Developers

RSS Feeds