Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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.
- #it works with directed only, so convert undirected to directed.
- #Negative Cycle detection: if the distance between ith node to the ith node is less than 0, It means there is a negative cycle.
- #User function template for Python
- inf=pow(10,8)
- class Solution:
- def floydWarshall(self, dist):
- n=len(dist)
- for via in range(n):
- for src in range(n):
- for dest in range(n):
- if dist[src][via]==inf or dist[via][dest]==inf: #There is no point of one distance of two route is infinity.
- continue
- dist[src][dest]=min(dist[src][dest], (dist[src][via]+dist[via][dest]))
- 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
- return [-1]
- return dist
Advertisement
Add Comment
Please, Sign In to add comment