This repository has been archived by the owner on Apr 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
floydwarshall.go
67 lines (60 loc) · 1.53 KB
/
floydwarshall.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright ©2015 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package search
import "github.com/gonum/graph"
// FloydWarshall returns a shortest-path tree for the graph g or false indicating
// that a negative cycle exists in the graph. If weight is nil and the graph does not
// implement graph.Coster, UniformCost is used.
//
// The time complexity of FloydWarshall is O(|V|^3).
func FloydWarshall(g graph.Graph, weight graph.CostFunc) (paths AllShortest, ok bool) {
var (
from = g.Neighbors
edgeTo func(graph.Node, graph.Node) graph.Edge
)
switch g := g.(type) {
case graph.DirectedGraph:
from = g.Successors
edgeTo = g.EdgeTo
default:
edgeTo = g.EdgeBetween
}
if weight == nil {
if g, ok := g.(graph.Coster); ok {
weight = g.Cost
} else {
weight = UniformCost
}
}
nodes := g.NodeList()
paths = newAllShortest(nodes, true)
for i, u := range nodes {
paths.dist.Set(i, i, 0)
for _, v := range from(u) {
j := paths.indexOf[v.ID()]
paths.set(i, j, weight(edgeTo(u, v)), j)
}
}
for k := range nodes {
for i := range nodes {
for j := range nodes {
ij := paths.dist.At(i, j)
joint := paths.dist.At(i, k) + paths.dist.At(k, j)
if ij > joint {
paths.set(i, j, joint, paths.at(i, k)...)
} else if ij-joint == 0 {
paths.add(i, j, paths.at(i, k)...)
}
}
}
}
ok = true
for i := range nodes {
if paths.dist.At(i, i) < 0 {
ok = false
break
}
}
return paths, ok
}