1

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.

  • To help others help you, my advice is to link to a statement of the algorithm which you are trying to implement (ideally pseudocode, not just a textual description), and give a very small (3 nodes is OK, can 2 nodes show the problem? can 1?), complete example (i.e. put your code in a class with a main program and tell people how to run it). – Robert Dodier Jul 05 '17 at 17:39
  • [This Link](http://www.sanfoundry.com/java-program-implement-floyd-warshall-algorithm/) may be helpful. – Manindar Jul 05 '17 at 17:50

1 Answers1

1

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.

Tobias Ribizel
  • 5,331
  • 1
  • 18
  • 33