|
| 1 | +### 3. Floyd-Warshall Algorithm - `floyd_warshall.py` |
| 2 | +**Description**: Computes shortest paths between **all pairs of vertices** in a weighted graph. |
| 3 | +It can handle **negative edge weights** (but no negative cycles) and works for both directed and undirected graphs. |
| 4 | + |
| 5 | +**Key Features**: |
| 6 | +- Finds shortest paths between every pair of vertices |
| 7 | +- Supports graphs with negative edge weights |
| 8 | +- Simple and easy-to-understand matrix-based implementation |
| 9 | +- Includes example usage for testing |
| 10 | + |
| 11 | +**Time Complexity**: O(V³), where V is the number of vertices |
| 12 | +**Space Complexity**: O(V²), for storing the distance matrix |
| 13 | + |
| 14 | +**Applications**: |
| 15 | +- Network routing and optimization |
| 16 | +- Finding shortest paths in road networks |
| 17 | +- Game AI pathfinding |
| 18 | +- All-pairs shortest distance analysis |
| 19 | + |
| 20 | +**Code Highlights**: |
| 21 | +```python |
| 22 | +from floyd_warshall import floyd_warshall |
| 23 | + |
| 24 | +graph = [ |
| 25 | + [0, 3, float('inf'), 7], |
| 26 | + [8, 0, 2, float('inf')], |
| 27 | + [5, float('inf'), 0, 1], |
| 28 | + [2, float('inf'), float('inf'), 0] |
| 29 | +] |
| 30 | + |
| 31 | +shortest_paths = floyd_warshall(graph) |
| 32 | +print("All pairs shortest path matrix:") |
| 33 | +for row in shortest_paths: |
| 34 | + print(row) |
| 35 | + |
| 36 | + |
| 37 | +All pairs shortest path matrix: |
| 38 | +[0, 3, 5, 7] |
| 39 | +[5, 0, 2, 4] |
| 40 | +[3, 6, 0, 1] |
| 41 | +[2, 5, 7, 0] |
| 42 | + |
| 43 | + |
| 44 | +Graph represented as adjacency matrix: |
| 45 | +- graph[i][j] = weight of edge from vertex i to j |
| 46 | +- float('inf') = no edge between i and j |
0 commit comments