Skip to content

Commit 0e6f8a9

Browse files
authored
Merge pull request #640 from saanidhi-git/add-floyd-warshall-python
[REQUEST] Add Floyd-Warshall Algorithm in Python ((#629)
2 parents 0e3db7d + 97b1823 commit 0e6f8a9

2 files changed

Lines changed: 87 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
Floyd Warshall Algorithm:
3+
4+
The Floyd Warshall algorithm finds the shortest distances between
5+
every pair of vertices in a weighted graph (both directed and undirected).
6+
7+
Time Complexity: O(V^3)
8+
Space Complexity: O(V^2)
9+
"""
10+
11+
def floyd_warshall(graph):
12+
"""
13+
graph: 2D list (adjacency matrix)
14+
graph[i][j] = weight from i → j or float('inf') if no edge.
15+
16+
Returns: dist - 2D list of shortest path distances.
17+
"""
18+
V = len(graph)
19+
dist = [row[:] for row in graph]
20+
21+
for k in range(V):
22+
for i in range(V):
23+
for j in range(V):
24+
if dist[i][k] + dist[k][j] < dist[i][j]:
25+
dist[i][j] = dist[i][k] + dist[k][j]
26+
return dist
27+
28+
29+
if __name__ == "__main__":
30+
INF = float('inf')
31+
graph = [
32+
[0, 3, INF, 5],
33+
[2, 0, INF, 4],
34+
[INF, 1, 0, INF],
35+
[INF, INF, 2, 0]
36+
]
37+
38+
result = floyd_warshall(graph)
39+
print("All-Pairs Shortest Paths:")
40+
for row in result:
41+
print(row)
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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

Comments
 (0)