imashutosh51

Floyd Warshall - all nodes to all nodes distance

Mar 23rd, 2026 (edited)
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. #Floyd warshall: It helps you to find the distance bw all node to all the other nodes unlike the Bellman and Djktra where we have a fixed source.
  2. #it works with directed only, so convert undirected to directed.
  3. #Negative Cycle detection: if the distance between ith node to the ith node is less than 0, It means there is a negative cycle.
  4.  
  5. #User function template for Python
  6. inf=pow(10,8)
  7. class Solution:
  8.     def floydWarshall(self, dist):
  9.         n=len(dist)
  10.        
  11.         for via in range(n):
  12.             for src in range(n):
  13.                 for dest in range(n):
  14.                     if dist[src][via]==inf or dist[via][dest]==inf: #There is no point of one distance of two route is infinity.
  15.                         continue
  16.                     dist[src][dest]=min(dist[src][dest], (dist[src][via]+dist[via][dest]))
  17.                     if dist[src][dest]<0 and src==dest: #This one avoid the negative cycle, because negative cycle will keep reducing the distance of a node to the same node
  18.                         return [-1]
  19.         return dist
  20.                    
Advertisement
Add Comment
Please, Sign In to add comment