I want to use the Floyd-Warshall algorithm to find the shortest path between two vertices. The matrix is in an ArrayList<ArrayList<Integer>>. It is always fairly small, such as a 4x4 or 8x8 matrix.
In my class, I have a distance matrix already. I'm just trying to create the "shortest path" matrix. But it doesn't work. It fills my matrix wrong.
I really hope someone can look at this and explain what's wrong.
My distance matrix is:
0 0 256 411
556 0 558 0
250 0 0 431
0 0 431 0
Test output is:
0 0 0 0
556 556 556 556
250 250 250 250
0 0 0 0
Expected:
500 0 842 681
556 0 806 967
0 0 500 681
581 0 0 862
I've commented out my test output. distance
is my matrix with the integer value of the distances between the vertices. In my matrix, i
is y and j
is x.
public ArrayList<ArrayList<Integer>> calcShortest() {
//String test = "";
ArrayList<ArrayList<Integer>> shortest = distance;
for (int k = 0; k < airports.size(); k++) {
for (int i = 0; i < airports.size(); i++) {
for (int j = 0; j < airports.size(); j++) {
shortest.get(j).add(i, Math.min(shortest.get(k).get(i) + shortest.get(j).get(k),
shortest.get(j).get(i)));
}
}
}
/*for (int j = 0; j < airports.size(); j++) {
for (int i = 0; i < airports.size(); i++) {
test += shortest.get(j).get(i) + " ";
}
System.out.println(test);
test = "";
}*/
return shortest;
}