Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions graphs/floyd_warshall.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
Floyd-Warshall Algorithm
Solves the all-pairs shortest path problem for a weighted graph.
"""

def floyd_warshall(dist):
"""
Updates the distance matrix to contain the shortest distances
between all pairs of vertices.

Check failure on line 10 in graphs/floyd_warshall.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

graphs/floyd_warshall.py:10:1: W293 Blank line contains whitespace
Args:
dist: 2D list, adjacency matrix where dist[i][j] is the weight
from vertex i to vertex j (use a large number for infinity)
"""
V = len(dist)

Check failure on line 15 in graphs/floyd_warshall.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N806)

graphs/floyd_warshall.py:15:5: N806 Variable `V` in function should be lowercase

# Consider each vertex as an intermediate point
for k in range(V):
for i in range(V):
for j in range(V):
# Update dist[i][j] if a shorter path is found through k
if dist[i][k] != INF and dist[k][j] != INF:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])


if __name__ == "__main__":
INF = 100000000 # Representation of "infinity"

Check failure on line 28 in graphs/floyd_warshall.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

graphs/floyd_warshall.py:28:1: W293 Blank line contains whitespace
# New example adjacency matrix
dist = [
[0, 3, INF, 7, INF],
[8, 0, 2, INF, INF],
[5, INF, 0, 1, INF],
[2, INF, INF, 0, 1],
[INF, INF, INF, INF, 0]
]

floyd_warshall(dist)

print("Shortest distances between all pairs of vertices:")
for row in dist:
print(row)
Loading