I've been trying for a week to get path finding to work for a game i'm working on. I'm using this implementation of Floyd Warshall's algorithm. I believe I've managed to narrow down the problem to be within this loop:
for(int k = 0; k < nodes.length; k++)
for(int i = 0; i < nodes.length; i++)
for(int j = 0; j < nodes.length; j++)
if(D[i][k] != Integer.MAX_VALUE
&& D[k][j] != Integer.MAX_VALUE
&& D[i][k] + D[k][j] < D[i][j]){
D[i][j] = D[i][k]+D[k][j];
P[i][j] = nodes[k];
}
I've been testing with 4 nodes were every node connects to all other nodes and all connections have a weight of 1. Here's the values of all relevant variables before the loop.
for(Node n:nodes)System.out.println(n.pos.toString() + " " + n.index);
Output:
[x: 4, y: 4] 0
[x: 4, y: 5] 1
[x: 5, y: 4] 2
[x: 5, y: 5] 3
This is as expected
for(Edge e:edgeList)
System.out.println(e.from.pos.toString() + " " + e.to.pos.toString());
Output:
[x: 4, y: 4] [x: 5, y: 4]
[x: 4, y: 4] [x: 4, y: 5]
[x: 4, y: 4] [x: 5, y: 5]
[x: 4, y: 5] [x: 4, y: 4]
[x: 4, y: 5] [x: 5, y: 4]
[x: 4, y: 5] [x: 5, y: 5]
[x: 5, y: 4] [x: 4, y: 4]
[x: 5, y: 4] [x: 4, y: 5]
[x: 5, y: 4] [x: 5, y: 5]
[x: 5, y: 5] [x: 4, y: 4]
[x: 5, y: 5] [x: 5, y: 4]
[x: 5, y: 5] [x: 4, y: 5]
This is also as expected.
for(int[] ia:D){
for(int a:ia)System.out.print(a + " ");
System.out.print("\n");
}
Output:
2147483647 1 1 1
1 2147483647 1 1
1 1 2147483647 1
1 1 1 2147483647
This is also as expected.
P = new Node[nodes.length][nodes.length];
for(int k = 0; k < nodes.length; k++)
for(i = 0; i < nodes.length; i++)
for(int j = 0; j < nodes.length; j++)
if(D[i][k] != Integer.MAX_VALUE
&& D[k][j] != Integer.MAX_VALUE
&& D[i][k]+D[k][j] < D[i][j]){
D[i][j] = D[i][k]+D[k][j];
P[i][j] = nodes[k];
System.out.println(nodes[k].pos.toString() + " " + k);
}
Output:
[x: 4, y: 4] 0
[x: 4, y: 4] 0
[x: 4, y: 4] 0
[x: 4, y: 5] 1
This is where i think the problem is, i expected the output to contain all the different nodes, only the two nodes found here work in the getShortestPath function. I believe this would be the correct output of the loop and the order should be irrelevant as far as i understand.
[x: 4, y: 4] 0
[x: 4, y: 5] 1
[x: 5, y: 4] 2
[x: 5, y: 5] 3
I have no idea what exactly causes the problem in the loop or if I've misunderstood something about the algorithm.