forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Floyd_Warshall_Algorithm.go
53 lines (45 loc) · 1.08 KB
/
Floyd_Warshall_Algorithm.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
package main
import (
"fmt"
"math"
)
func floyd_warshall(graph [][]float64) [][]float64 {
dist := make([][]float64, len(graph))
// Initialises a distance matrix
for i := range graph {
dist[i] = make([]float64, len(graph))
}
for i := range graph {
for j := range graph[i] {
dist[i][j] = graph[i][j]
}
}
// Implements the Floyd Warshall Algorithm
for k := range dist {
for i := range dist {
for j := range dist {
if dij := dist[i][k] + dist[k][j]; dij < dist[i][j] {
dist[i][j] = dij
}
}
}
}
return dist
}
func main() {
graph := [][]float64{
{0, 5, math.Inf(1), 10},
{math.Inf(1), 0, 3, math.Inf(1)},
{math.Inf(1), math.Inf(1), 0, 1},
{math.Inf(1), math.Inf(1), math.Inf(1), 0},
}
dist := floyd_warshall(graph)
for _, d := range dist {
fmt.Printf("%4g\n", d)
}
}
//OUTPUT
//[ 0 5 8 9]
//[+Inf 0 3 4]
//[+Inf +Inf 0 1]
//[+Inf +Inf +Inf 0]