graph/path: indicate negative cycle weights with -Inf instead of NaN

The paths are undefined, but the limit of the path weight is -Inf.
This commit is contained in:
Dan Kortschak
2019-02-07 20:57:33 +10:30
parent 936e3fec9e
commit ee7dd3742a
3 changed files with 14 additions and 14 deletions

View File

@@ -13,7 +13,7 @@ import (
// FloydWarshall returns a shortest-path tree for the graph g or false indicating
// that a negative cycle exists in the graph. If a negative cycle exists in the graph
// the returned paths will be valid and edge weights on the negative cycle will be
// set to NaN. If the graph does not implement Weighted, UniformCost is used.
// set to -Inf. If the graph does not implement Weighted, UniformCost is used.
//
// The time complexity of FloydWarshall is O(|V|^3).
func FloydWarshall(g graph.Graph) (paths AllShortest, ok bool) {
@@ -65,7 +65,7 @@ func FloydWarshall(g graph.Graph) (paths AllShortest, ok bool) {
if !ok {
// If we have a negative cycle, mark all
// the edges in the cycles with NaN weight.
// the edges in the cycles with -Inf weight.
d := paths.dist
for i := range nodes {
for j := range nodes {
@@ -73,9 +73,9 @@ func FloydWarshall(g graph.Graph) (paths AllShortest, ok bool) {
if math.IsInf(d.At(i, k), 1) || math.IsInf(d.At(k, j), 1) {
continue
}
if d.At(k, k) < 0 || math.IsNaN(d.At(k, k)) {
d.Set(k, k, math.NaN())
d.Set(i, j, math.NaN())
if d.At(k, k) < 0 {
d.Set(k, k, math.Inf(-1))
d.Set(i, j, math.Inf(-1))
}
}
}