3

I am using this Floyd-Warshall algorithm from here.

import static java.lang.String.format;
import java.util.Arrays;



public class FloydWarshall {


    public static void main(String[] args) {
        int[][] weights = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}};
        int numVertices = 4;

        floydWarshall(weights, numVertices);
    }

    static void floydWarshall(int[][] weights, int numVertices) {

        double[][] dist = new double[numVertices][numVertices];
        for (double[] row : dist)
            Arrays.fill(row, Double.POSITIVE_INFINITY);

        for (int[] w : weights)
            dist[w[0] - 1][w[1] - 1] = w[2];

        int[][] next = new int[numVertices][numVertices];
        for (int i = 0; i < next.length; i++) {
            for (int j = 0; j < next.length; j++)
                if (i != j)
                    next[i][j] = j + 1;
        }

        for (int k = 0; k < numVertices; k++)
            for (int i = 0; i < numVertices; i++)
                for (int j = 0; j < numVertices; j++)
                    if (dist[i][k] + dist[k][j] < dist[i][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j];
                        next[i][j] = next[i][k];
                    }

        printResult(dist, next);
    }

    static void printResult(double[][] dist, int[][] next) {
        System.out.println("pair     dist    path");
        for (int i = 0; i < next.length; i++) {
            for (int j = 0; j < next.length; j++) {
                if (i != j) {
                    int u = i + 1;
                    int v = j + 1;
                    String path = format("%d -> %d    %2d     %s", u, v,
                            (int) dist[i][j], u);
                    do {
                        u = next[u - 1][v - 1];
                        path += " -> " + u;
                    } while (u != v);
                    System.out.println(path);
                }
            }
        }
    }
}

The algorithm itself is quite clear but what I don't understand is the next matrix. From my understanding on i,j indexes should be the last preceding node on the path from node i to node j. Printing path is then printed recursively. But this piece of code uses some kind of different approach in the printing statement printResult. So my question is what exactly is the matrix next and how does the printing work?

1 Answers1

0

the line dist[i][j] = dist[i][k] + dist[k][j] says : when going from i to j, go through k, taking the shortest path from i to k, and then the shortest path from k to j. Here : next[i][j] = next[i][k] it says that when going from i to j, first go where you would go if you went from i to k.

So, the line u = next[u - 1][v - 1]; says: u is now the next node on the path from u to v.

maniek
  • 7,087
  • 2
  • 20
  • 43