Skip to content

Commit 13cba6b

Browse files
authored
Merge pull request #143 from iko1133/add-floyd-warshall-graphs
Added implementation of Floyd-Warshall algorithm
2 parents 6fcebd1 + 48bb154 commit 13cba6b

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

DIRECTORY.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@
2929
* [Matrix-Multiplication](https://github.com/TheAlgorithms/Go/blob/master/dynamic-programming/matrix-multiplication.go)
3030
* [Rod-Cutting](https://github.com/TheAlgorithms/Go/blob/master/dynamic-programming/rod-cutting.go)
3131

32+
## Graphs
33+
* [Floyd-Warshall algorithm](https://github.com/TheAlgorithms/Go/blob/master/graphs/floyd_warshall.go)
34+
3235
## Other
3336
* [Maxsubarraysum](https://github.com/TheAlgorithms/Go/blob/master/other/maxSubarraySum.go)
3437
* [Nestedbrackets](https://github.com/TheAlgorithms/Go/blob/master/other/NestedBrackets.go)

graphs/floyd_warshall.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Floyd-Warshall algorithm
2+
// https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm
3+
4+
package graph
5+
6+
import (
7+
"math"
8+
)
9+
10+
// Defining matrix to use 2d array easier
11+
type Matrix [][]float64
12+
13+
// Defining maximum value. If two vertices share this value, it means they are not connected
14+
var maxValue = math.Inf(1)
15+
16+
// Returns all pair's shortest path using Floyd Warshall algorithm
17+
func FloydWarshall(graph Matrix) Matrix {
18+
// If graph is empty or width != height, returns nil
19+
if len(graph) == 0 || len(graph) != len(graph[0]) {
20+
return nil
21+
}
22+
23+
numVertecies := len(graph)
24+
25+
// Initializing result matrix and filling it up with same values as given graph
26+
result := make(Matrix, numVertecies)
27+
28+
for i := 0; i < numVertecies; i++ {
29+
result[i] = make([]float64, numVertecies)
30+
for j := 0; j < numVertecies; j++ {
31+
result[i][j] = graph[i][j]
32+
}
33+
}
34+
35+
// Running over the result matrix and following the algorithm
36+
for k := 0; k < numVertecies; k++ {
37+
for i := 0; i < numVertecies; i++ {
38+
for j := 0; j < numVertecies; j++ {
39+
// If there is a less costly path from i to j node, remembering it
40+
if result[i][j] > result[i][k]+result[k][j] {
41+
result[i][j] = result[i][k] + result[k][j]
42+
}
43+
}
44+
}
45+
}
46+
47+
return result
48+
}
49+
50+
// func main() {
51+
// var graph Matrix
52+
// graph = Matrix{{0, maxValue, -2, maxValue},
53+
// {4, 0, 3, maxValue},
54+
// {maxValue, maxValue, 0, 2},
55+
// {maxValue, -1, maxValue, 0}}
56+
57+
// result := FloydWarshall(graph)
58+
59+
// // Print result
60+
// for i := 0; i < len(result); i++ {
61+
// fmt.Printf("%4g\n", result[i])
62+
// }
63+
// }

0 commit comments

Comments
 (0)