|
| 1 | +// FloydWarshall.go |
| 2 | +// |
| 3 | +// Floyd–Warshall Algorithm - All-Pairs Shortest Path |
| 4 | +// |
| 5 | +// Description: |
| 6 | +// The Floyd–Warshall algorithm computes the shortest paths between |
| 7 | +// all pairs of vertices in a weighted directed graph. It can handle |
| 8 | +// negative edge weights (but not negative cycles). |
| 9 | +// |
| 10 | +// Purpose / Use cases: |
| 11 | +// - Network routing, transitive closure, and distance computation. |
| 12 | +// - Detect negative cycles in graphs. |
| 13 | +// |
| 14 | +// Approach / Methodology: |
| 15 | +// - Dynamic Programming approach. |
| 16 | +// - Initialize a distance matrix with given edge weights. |
| 17 | +// - Iteratively relax edges by trying all intermediate vertices. |
| 18 | +// |
| 19 | +// Complexity Analysis: |
| 20 | +// - Time: O(V³) |
| 21 | +// - Space: O(V²) |
| 22 | +// |
| 23 | +// File contents: |
| 24 | +// - FloydWarshall() function. |
| 25 | +// - PrintDistanceMatrix() utility. |
| 26 | +// - Example test in main(). |
| 27 | + |
| 28 | +package main |
| 29 | + |
| 30 | +import ( |
| 31 | + "fmt" |
| 32 | + "math" |
| 33 | +) |
| 34 | + |
| 35 | +// FloydWarshall computes all-pairs shortest paths. |
| 36 | +// It modifies and returns the distance matrix. |
| 37 | +func FloydWarshall(dist [][]float64) [][]float64 { |
| 38 | + n := len(dist) |
| 39 | + for k := 0; k < n; k++ { |
| 40 | + for i := 0; i < n; i++ { |
| 41 | + for j := 0; j < n; j++ { |
| 42 | + if dist[i][k]+dist[k][j] < dist[i][j] { |
| 43 | + dist[i][j] = dist[i][k] + dist[k][j] |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + return dist |
| 49 | +} |
| 50 | + |
| 51 | +// PrintDistanceMatrix prints a formatted distance matrix. |
| 52 | +func PrintDistanceMatrix(dist [][]float64) { |
| 53 | + fmt.Println("All-Pairs Shortest Path Matrix:") |
| 54 | + for _, row := range dist { |
| 55 | + for _, val := range row { |
| 56 | + if val == math.Inf(1) { |
| 57 | + fmt.Printf("%4s ", "INF") |
| 58 | + } else { |
| 59 | + fmt.Printf("%4.0f ", val) |
| 60 | + } |
| 61 | + } |
| 62 | + fmt.Println() |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// main runs an example directed graph for Floyd–Warshall. |
| 67 | +func main() { |
| 68 | + fmt.Println("Floyd–Warshall Algorithm Demo") |
| 69 | + |
| 70 | + const INF = math.Inf(1) |
| 71 | + dist := [][]float64{ |
| 72 | + {0, 3, INF, 7}, |
| 73 | + {8, 0, 2, INF}, |
| 74 | + {5, INF, 0, 1}, |
| 75 | + {2, INF, INF, 0}, |
| 76 | + } |
| 77 | + |
| 78 | + result := FloydWarshall(dist) |
| 79 | + PrintDistanceMatrix(result) |
| 80 | +} |
0 commit comments