1+ # Python program for Bellman-Ford's single source
2+ # shortest path algorithm.
3+
4+ from collections import defaultdict
5+
6+ #Class to represent a graph
7+ class Graph :
8+
9+ def __init__ (self ,vertices ):
10+ self .V = vertices #No. of vertices
11+ self .graph = [] # default dictionary to store graph
12+
13+ # function to add an edge to graph
14+ def addEdge (self ,u ,v ,w ):
15+ self .graph .append ([u , v , w ])
16+
17+ # utility function used to print the solution
18+ def printArr (self , dist ):
19+ print ("Vertex Distance from Source" )
20+ for i in range (self .V ):
21+ print ("%d \t \t %d" % (i , dist [i ]))
22+
23+ # The main function that finds shortest distances from src to
24+ # all other vertices using Bellman-Ford algorithm. The function
25+ # also detects negative weight cycle
26+ def BellmanFord (self , src ):
27+
28+ # Step 1: Initialize distances from src to all other vertices
29+ # as INFINITE
30+ dist = [float ("Inf" )] * self .V
31+ dist [src ] = 0
32+
33+
34+ # Step 2: Relax all edges |V| - 1 times. A simple shortest
35+ # path from src to any other vertex can have at-most |V| - 1
36+ # edges
37+ for i in range (self .V - 1 ):
38+ # Update dist value and parent index of the adjacent vertices of
39+ # the picked vertex. Consider only those vertices which are still in
40+ # queue
41+ for u , v , w in self .graph :
42+ if dist [u ] != float ("Inf" ) and dist [u ] + w < dist [v ]:
43+ dist [v ] = dist [u ] + w
44+
45+ # Step 3: check for negative-weight cycles. The above step
46+ # guarantees shortest distances if graph doesn't contain
47+ # negative weight cycle. If we get a shorter path, then there
48+ # is a cycle.
49+
50+ for u , v , w in self .graph :
51+ if dist [u ] != float ("Inf" ) and dist [u ] + w < dist [v ]:
52+ print "Graph contains negative weight cycle"
53+ return
54+
55+ # print all distance
56+ self .printArr (dist )
57+
58+ g = Graph (5 )
59+ g .addEdge (0 , 1 , - 1 )
60+ g .addEdge (0 , 2 , 4 )
61+ g .addEdge (1 , 2 , 3 )
62+ g .addEdge (1 , 3 , 2 )
63+ g .addEdge (1 , 4 , 2 )
64+ g .addEdge (3 , 2 , 5 )
65+ g .addEdge (3 , 1 , 1 )
66+ g .addEdge (4 , 3 , - 3 )
67+
68+ #Print the solution
69+ g .BellmanFord (0 )
0 commit comments