Skip to content

Commit fa93076

Browse files
aws-masterthuva4
authored andcommitted
Added Floyd's Algorithm in Go (thuva4#504)
1 parent 554754c commit fa93076

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Floyd–Warshall in Golang
2+
package main
3+
4+
import (
5+
"fmt"
6+
"math"
7+
)
8+
9+
type graph struct {
10+
to int
11+
wt float64
12+
}
13+
14+
func floydWarshall(g [][]graph) [][]float64 {
15+
dist := make([][]float64, len(g))
16+
for i := range dist {
17+
di := make([]float64, len(g))
18+
for j := range di {
19+
di[j] = math.Inf(1)
20+
}
21+
di[i] = 0
22+
dist[i] = di
23+
}
24+
for u, graphs := range g {
25+
for _, v := range graphs {
26+
dist[u][v.to] = v.wt
27+
}
28+
}
29+
for k, dk := range dist {
30+
for _, di := range dist {
31+
for j, dij := range di {
32+
if d := di[k] + dk[j]; dij > d {
33+
di[j] = d
34+
}
35+
}
36+
}
37+
}
38+
return dist
39+
}
40+
41+
func main() {
42+
gra := [][]graph{
43+
1: {{2, 3}, {3, 8},{5, -4}},
44+
2: {{4, 1}, {5, 7}},
45+
3: {{2, 4}},
46+
4: {{1, 2}, {3, -5}},
47+
5: {{4, 6}},
48+
}
49+
50+
dist := floydWarshall(gra)
51+
//dist[][] will be the output matrix that will finally
52+
//have the shortest distances between every pair of vertices
53+
for _, d := range dist {
54+
fmt.Printf("%4g\n", d)
55+
}
56+
}
57+
58+
// Source : http://www.golangprograms.com/golang-program-for-implementation-of-floyd-warshall-algorithm.html

0 commit comments

Comments
 (0)