0

I'm having difficulties implementing the Floyd-Warshall algorithm for a self project I'm trying to figure out. I have a test set of data, but as I'm printing it out after ShortestPath is created, I just get a null and a memory address. Not sure exactly where to go with this algorithm from here. Any assistance is greatly appreciated!

public static void main(String[] args) {
    int x = Integer.MAX_VALUE;
    int[][] adj = {{ 0, 3, 8, x, 4 },
                   { x, 0, x, 1, 7 },
                   { x, 4, 0, x, x },
                   { 2, x, 5, 0, x },
                   { x, x, x, 6, 0 }};
    ShortestPath sp = new ShortestPath(adj);
    System.out.println(sp);
}

public class ShortestPath {

private int[][] adj;
private int[][] spTable;
private int n;

public static void copy(int[][] a, int[][] b) {
    for (int i=0; i < a.length; i++)
        for (int j = 0; j < a[0].length; j++)
            a[i][j] = b[i][j];
}

public ShortestPath(int[][] adj) {
    n = adj.length;
    this.spTable = new int[n][n];
    copy(this.spTable, adj);

    for(int k = 0; k < n; k++) {
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if (spTable[i][k] + spTable[k][j] < spTable[i][j]) {
                    spTable[i][j] = spTable[i][k] + spTable[k][j];
                    adj[i][j] = adj[k][j];
                }
            }
        }
    }
}


@Override
public String toString() {
    return adj + "\n\n" + spTable + "";
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138

1 Answers1

0
public ShortestPath(int[][] adj)

The parameter adj you're passing here is shadowing your adj class member - you never give the class member a value. A simple fix is to put the following line of code anywhere in the above constructor:

this.adj = adj;

See this for more.


Another problem is here:

return adj + "\n\n" + spTable + "";

You can't print the values in an array by just adding it to a string - that will just print the address.

You need a double-for-loop to print the values in an array. See this question for more details.

Community
  • 1
  • 1
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138