|
| 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