imashutosh51

Bellman-Ford- distance bw src to all nodes with negative edges

Mar 23rd, 2026 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. '''
  2. Dijktra doesn't work with the negative edges graphs, if there is a path weight or full cycle distance is less than 0, It will go for TLE.
  3. #Bellman ford algorithm only works with the Directed graph, so if we are having the Undirected, make it directed graph but adding two edges,a->b and b->a.
  4. #Bellman ford doesn't work with a negative cycle.
  5. #Do the N-1 iteration where each iteration will relax the edges given N=Number of vertices and edges can be in any order.
  6. #Why N-1 iteration? Because In worst case, it might take you N-1 iteration to find distance from source to all the nodes.
  7. #How to detect a negative cycle in the graph? -> If the distance array gets updated at Nth iteration also, It is having a negative cycle loop because negative cycle will be having some negative value for eg. -1 then every iteration will reduce the distance by -1.
  8.  
  9. Why do we only visit n-1 times only?
  10. because The longest possible shortest path in a graph can contain at most n-1 edges.a shortest path cannot keep revisiting nodes (that would create a cycle).
  11.  
  12. '''
  13. # from math import inf
  14. INF=pow(10,8)
  15. class Solution:
  16.     def bellmanFord(self, v, edges, src):
  17.         dist=[INF]*v
  18.         dist[src]=0
  19.         for i in range(v): #It will iterate V times but we need only v-1 times so we kept vth iteration to check the negative cycle.
  20.             for a,b,w in edges:
  21.                 if dist[a]==INF:
  22.                     continue
  23.                 if dist[a]+w<dist[b]:
  24.                     if i==v-1:
  25.                         return [-1]
  26.                     dist[b]=dist[a]+w #if the distance also got relaxed in last iteration ie. vth iteration means there is negative cycle.
  27.                    
  28.         return dist
  29.  
Advertisement
Add Comment
Please, Sign In to add comment