FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm
(graph WeightedGraph)
| 15 | |
| 16 | // FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm |
| 17 | func FloydWarshall(graph WeightedGraph) WeightedGraph { |
| 18 | // If graph is empty, returns nil |
| 19 | if len(graph) == 0 || len(graph) != len(graph[0]) { |
| 20 | return nil |
| 21 | } |
| 22 | |
| 23 | for i := 0; i < len(graph); i++ { |
| 24 | //If graph matrix width is different than the height, returns nil |
| 25 | if len(graph[i]) != len(graph) { |
| 26 | return nil |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | numVertices := len(graph) |
| 31 | |
| 32 | // Initializing result matrix and filling it up with same values as given graph |
| 33 | result := make(WeightedGraph, numVertices) |
| 34 | |
| 35 | for i := 0; i < numVertices; i++ { |
| 36 | result[i] = make([]float64, numVertices) |
| 37 | for j := 0; j < numVertices; j++ { |
| 38 | result[i][j] = graph[i][j] |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // Running over the result matrix and following the algorithm |
| 43 | for k := 0; k < numVertices; k++ { |
| 44 | for i := 0; i < numVertices; i++ { |
| 45 | for j := 0; j < numVertices; j++ { |
| 46 | // If there is a less costly path from i to j node, remembering it |
| 47 | if result[i][j] > result[i][k]+result[k][j] { |
| 48 | result[i][j] = result[i][k] + result[k][j] |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return result |
| 55 | } |
no outgoing calls