Floyd-Warsall Algorithm - Representation of "Infinity"

Using the Floyd-Warsall algorithm to find the shortest path between two vertices, how should I represent infinity when implemented in Java? I use infinity here to say that there is no way between the two peaks.

thank

+4
source share
2 answers

The answer depends on the type of data you use to represent the weight. If so double, you can use Double.POSITIVE_INFINITY. If it is an integer, select a value that you are not using, for example. negative if your graph does not allow negative edges.

, : , "" , , "" :

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;
            }
        }
    }
}
+4

Integer/Long Float/Double, int/Long Float/Double, null .

+1

Source: https://habr.com/ru/post/1540072/


All Articles