Skip to content

Commit

Permalink
Floyd Warshell Algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
muthuspark committed Nov 7, 2023
1 parent 1650680 commit 29be519
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@
| B* Search | ✔️ |
| Kruskals Algorithm | ✔️ |
| Prims Algorithm | ✔️ |
| Floyd Warshell Algorithm | ✔️ |
32 changes: 32 additions & 0 deletions search/floyd-warshall.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
def floyd_warshall(graph):
n = len(graph)

# Initialize the distance matrix with the graph's adjacency matrix
distance = [row[:] for row in graph]
print(distance)
# Loop through all vertices as intermediate nodes
for k in range(n):
# Pick all vertices as source one by one
for i in range(n):
# Pick all vertices as destination for the above source
for j in range(n):
# If the new path through k is shorter, update the distance
print(f"i={i}, j={j}, k={k} {distance[i][k]} + {distance[k][j]} < {distance[i][j]}")
if distance[i][k] + distance[k][j] < distance[i][j]:
distance[i][j] = distance[i][k] + distance[k][j]
print(f"distance = {distance}")

return distance

# Example adjacency matrix for a graph with 4 nodes (0, 1, 2, 3)
INF = float('inf')
graph = [
[0, 5, 9, 3],
[2, 0, 4, INF],
[INF, INF, 0, 3],
[2, INF, INF, 0]
]

result = floyd_warshall(graph)
for row in result:
print(row)

0 comments on commit 29be519

Please sign in to comment.