// Floyd-Warshall algorithm - iterative version // // Author: Rahul Simha // Date: Oct, 2001. public class FloydWarshallIter { int numVertices; // Number of vertices (when initialized). double[][] adjMatrix; // The adjacency matrix (given as input). double[][] D; // Matrix used in dynamic programming. public void initialize (int numVertices) { this.numVertices = numVertices; // Initialize Dk matrices. D = new double [numVertices][]; for (int i=0; i < numVertices; i++){ D[i] = new double [numVertices]; } } public void allPairsShortestPaths (double[][] adjMatrix) { // D = weights when k = -1 for (int i=0; i 0) D[i][j] = adjMatrix[i][j]; else D[i][j] = Double.MAX_VALUE; } else { // NOTE: we are setting D[i][j] = 0 whether or not // the adjMatrix has the same value (a precaution). D[i][j] = 0; } } } // We will stop when there are no further changes // Therefore, we need a variable to track whether a changed occured. boolean changeOccurred = true; // Repeat until no more changes. while (changeOccurred) { changeOccurred = false; for (int i=0; i 0) ) { // If it's better via j, then reflect the new cost. if (D[j][d] + adjMatrix[i][j] < D[i][d]) { D[i][d] = D[j][d] + adjMatrix[i][j]; // Change has occured, which may propagate. changeOccurred = true; } } } // end-inner-for } //end if } //end-for } // end-for } // end-while // ... path construction (not shown) ... } public static void main (String[] argv) { // A test case. double[][] adjMatrix = { {0, 1, 7, 0, 5, 0, 1}, {1, 0, 1, 0, 0, 7, 0}, {7, 1, 0, 1, 7, 0, 0}, {0, 0, 1, 0, 1, 0, 0}, {5, 0, 7, 1, 0, 1, 0}, {0, 7, 0, 0, 1, 0, 1}, {1, 0, 0, 0, 0, 1, 0}, }; int n = adjMatrix.length; FloydWarshallIter fwAlg = new FloydWarshallIter (); fwAlg.initialize (n); fwAlg.allPairsShortestPaths (adjMatrix); // ... print paths (not shown) ... } }