5

Using Floyd-Warshall's algorithm for finding the shortest path between two vertices, how should I represent infinity when implementing in Java? I'm using infinity here to say there is no path between two vertices.

Thanks

DJDMorrison
  • 1,302
  • 2
  • 17
  • 34

2 Answers2

5

The answer depends on the data type that you use to represent the weight. If it is double, you would be safe to use Double.POSITIVE_INFINITY. If it is an integer, pick a value that you do not use, e.g. negative one if your graph does not allow negative edges.

An unfortunate consequence of this is that you would need to pay attention to the infinity element inside the three loops: rather than using the "straight" addition, you would need to check if it's the special "infinity" value, and only then do the addition:

final int INFINITY = -1;
...
for (int k = 0 ; k != N ; k++) {
    for (int i = 0 ; i != N ; i++) {
        for (int j = 0 ; j != N ; j++) {
            if (g[i][k] == INFINITY || g[k][j] == INFINITY) continue;
            int total = g[i][k] + g[k][j];
            if (g[i][j] != INFINITY) {
                g[i][j] = Math.min(g[i][j], total);
            } else {
                g[i][j] = total;
            }
        }
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • If we are using an Integer, and we don't want to make checks that the element is INFINITY/ null etc. Could we use Integer.MAX_VALUE? As when it does the Math.min evaluation, the other value will always be smaller. – DJDMorrison May 10 '14 at 21:56
  • @DJDMorrison No, you cannot use `Integer.MAX_VALUE` without an additional check, because adding anything to `Integer.MAX_VALUE` results in overflow. This would cause incorrect results when you compare `g[i][j]` and `g[i][k]+g[k][j]`. – Sergey Kalinichenko May 10 '14 at 21:58
  • Since you *are* making sure you are not summing anything to `INFINITY`, you may as well write this `INFINITY = Integer.MAX_VALUE`. – Agostino Apr 03 '15 at 22:42
1

If you use Integer/Long or Float/Double and not int/long or float/double, then you can you the null value to represent infinity.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159