Advertisement
Eternoseeker

Ch-Assignment3-FloydWarshall

Nov 24th, 2023
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | Source Code | 0 0
  1. def floyd_warshall(graph):
  2.     n = len(graph)
  3.     # all distances are set to infinity at starting
  4.     dist = [[float('inf')] * n for _ in range(n)]
  5.    
  6.     # diagonal elements set to 0
  7.     for i in range(n):
  8.         dist[i][i] = 0
  9.  
  10.     for u in range(n):
  11.         for v in range(n):
  12.             if u != v and graph[u][v] != float('inf'):
  13.                 dist[u][v] = graph[u][v]
  14.    
  15.     # They iterate through all possible vertices k, i, and j to consider if there is a
  16.     # shorter path from vertex i to vertex j through vertex k
  17.  
  18.     for k in range(n):
  19.         for i in range(n):
  20.             for j in range(n):
  21.                 if dist[i][j] > dist[i][k] + dist[k][j]:
  22.                     dist[i][j] = dist[i][k] + dist[k][j]
  23.  
  24.     return dist
  25.  
  26. # Input-driven code
  27. if __name__ == "__main__":
  28.     num_vertices = int(input("Enter the number of vertices: "))
  29.     Infinity = float('inf')
  30.     graph = [[Infinity] * num_vertices for _ in range(num_vertices)]
  31.  
  32.     for i in range(num_vertices):
  33.         for j in range(num_vertices):
  34.             weight_input = input(f"Enter the weight from vertex {i+1} to vertex {j+1}: ")
  35.             if weight_input.lower() == 'inf':
  36.                 graph[i][j] = Infinity
  37.             else:
  38.                 graph[i][j] = float(weight_input)
  39.  
  40.     result = floyd_warshall(graph)
  41.     for row in result:
  42.         print(row)
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement