I got the following implementation for Floyd's algorithm, which is used to find shortest paths in a weighted graph. The result is a matrix of the shortest paths between all vertices:
class FloydWarshall {
static int graph [][] = { {0, 5, 3},
{5, 0, 0},
{3, 0, 0}
};
public static void main(String args[]) {
int N=graph.length;
int y, x, j;
for (y = 0; y < N; y++)
for (x = 0; x < N; x++)
if (graph[x][y] > 0)
for (j = 0; j < N; j++)
if (graph[y][j] > 0)
if ((graph[x][j] == 0) || (graph[x][y] + graph[y][j] < graph[x][j]))
graph[x][j] = graph[x][y]+graph[y][j];
for (y = 0; y < N; y++) {
for (x = 0; x < N; x++)
System.out.print(graph[y][x] < 0 ? " "+graph[y][x] : " "+graph[y][x]);
System.out.println();
}
}
}
The weird thing is even though it is working, it doesn't calculate the right distance from a vertice to itself (which should be 0) for undirected graphs. For example the following graph:
{0, 5, 3}
{5, 0, 0}
{3, 0, 0}
gets the output:
6 5 3
5 10 8
3 8 6
instead of:
0 5 3
5 0 8
3 8 0
I assume there is just a stupid mistake in the code but I'm unable to find it so I am thankful for any help.