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.
The problem is the following: You are using the value 0 in two opposite ways in your implementation:
To signal that there exists no edge between x
and y
, you set graph[x][y]
to 0, as witnessed by the checks if (graph[x][y] > 0)
, if (graph[y][j] > 0)
To signal distance 0 between two nodes.
So your resulting diagonal entries actually tell you: What is the shortest non-trivial cycle involving my vertex?
I would recommend that you either use a very large number ( Integer.MAX_VALUE
, watch out for overflows!) to denote non-edges or better: store the adjacency information in a completely separate matrix.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.