File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Floyd-Warshall Algorithm
3+ Solves the all-pairs shortest path problem for a weighted graph.
4+ """
5+
6+ def floyd_warshall (dist ):
7+ """
8+ Updates the distance matrix to contain the shortest distances
9+ between all pairs of vertices.
10+
11+ Args:
12+ dist: 2D list, adjacency matrix where dist[i][j] is the weight
13+ from vertex i to vertex j (use a large number for infinity)
14+ """
15+ V = len (dist )
16+
17+ # Consider each vertex as an intermediate point
18+ for k in range (V ):
19+ for i in range (V ):
20+ for j in range (V ):
21+ # Update dist[i][j] if a shorter path is found through k
22+ if dist [i ][k ] != INF and dist [k ][j ] != INF :
23+ dist [i ][j ] = min (dist [i ][j ], dist [i ][k ] + dist [k ][j ])
24+
25+
26+ if __name__ == "__main__" :
27+ INF = 100000000 # Representation of "infinity"
28+
29+ # New example adjacency matrix
30+ dist = [
31+ [0 , 3 , INF , 7 , INF ],
32+ [8 , 0 , 2 , INF , INF ],
33+ [5 , INF , 0 , 1 , INF ],
34+ [2 , INF , INF , 0 , 1 ],
35+ [INF , INF , INF , INF , 0 ]
36+ ]
37+
38+ floyd_warshall (dist )
39+
40+ print ("Shortest distances between all pairs of vertices:" )
41+ for row in dist :
42+ print (row )
You can’t perform that action at this time.
0 commit comments