Skip to content

Commit acf9812

Browse files
authored
Merge pull request #629 from PranathiNagisetti/floyd_warshall_algo
Add Floyd-Warshall algorithm to Python graph algorithms
2 parents a2dd6ed + 3af9b10 commit acf9812

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
""""
2+
Purpose: Finds the shortest paths between all pairs of vertices in a weighted graph (can handle negative weights but no negative cycles)."""
3+
# Floyd-Warshall Algorithm in Python
4+
# Function to implement Floyd-Warshall Algorithm
5+
def floyd_warshall(graph):
6+
"""
7+
graph: 2D list of edge weights (adjacency matrix)
8+
graph[i][j] = weight of edge from i to j, or float('inf') if no edge
9+
Returns: 2D list with shortest distances between all pairs
10+
"""
11+
# Number of vertices
12+
V = len(graph)
13+
14+
# Initialize distance matrix same as graph
15+
dist = [list(row) for row in graph] # deep copy
16+
17+
# Add all vertices one by one as intermediate vertices
18+
for k in range(V):
19+
for i in range(V):
20+
for j in range(V):
21+
# Update dist[i][j] if going through k is shorter
22+
if dist[i][k] + dist[k][j] < dist[i][j]:
23+
dist[i][j] = dist[i][k] + dist[k][j]
24+
25+
return dist
26+
27+
# Utility function to print the distance matrix
28+
def print_matrix(dist):
29+
V = len(dist)
30+
print("Shortest distances between every pair of vertices:")
31+
for i in range(V):
32+
for j in range(V):
33+
if dist[i][j] == float('inf'):
34+
print("INF", end="\t")
35+
else:
36+
print(dist[i][j], end="\t")
37+
print()
38+
39+
# Main function
40+
if __name__ == "__main__":
41+
# Example graph represented as adjacency matrix
42+
INF = float('inf')
43+
graph = [
44+
[0, 3, INF, 5],
45+
[2, 0, INF, 4],
46+
[INF, 1, 0, INF],
47+
[INF, INF, 2, 0]
48+
]
49+
50+
# Compute shortest paths
51+
shortest_distances = floyd_warshall(graph)
52+
53+
# Print the result
54+
print_matrix(shortest_distances)

0 commit comments

Comments
 (0)