문제

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

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top