File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ def printDist (dist , V ):
2
+ print ("\n Vertex Distance" )
3
+ for i in range (V ):
4
+ if dist [i ] != float ('inf' ) :
5
+ print (i ,"\t " ,int (dist [i ]),end = "\t " )
6
+ else :
7
+ print (i ,"\t " ,"INF" ,end = "\t " )
8
+ print ();
9
+
10
+ def BellmanFord (graph , V , E , src ):
11
+ mdist = [float ('inf' ) for i in range (V )]
12
+ mdist [src ] = 0.0 ;
13
+
14
+ for i in range (V - 1 ):
15
+ for j in range (V ):
16
+ u = graph [j ]["src" ]
17
+ v = graph [j ]["dst" ]
18
+ w = graph [j ]["weight" ]
19
+
20
+ if mdist [u ] != float ('inf' ) and mdist [u ] + w < mdist [v ]:
21
+ mdist [v ] = mdist [u ] + w
22
+ for j in range (V ):
23
+ u = graph [j ]["src" ]
24
+ v = graph [j ]["dst" ]
25
+ w = graph [j ]["weight" ]
26
+
27
+ if mdist [u ] != float ('inf' ) and mdist [u ] + w < mdist [v ]:
28
+ print ("Negative cycle found. Solution not possible." )
29
+ return
30
+
31
+ printDist (mdist , V )
32
+
33
+
34
+
35
+ #MAIN
36
+ V = int (input ("Enter number of vertices: " ));
37
+ E = int (input ("Enter number of edges: " ));
38
+
39
+ graph = [dict () for j in range (E )]
40
+
41
+ for i in range (V ):
42
+ graph [i ][i ] = 0.0 ;
43
+
44
+ for i in range (E ):
45
+ print ("\n Edge " ,i + 1 )
46
+ src = int (input ("Enter source:" ))
47
+ dst = int (input ("Enter destination:" ))
48
+ weight = float (input ("Enter weight:" ))
49
+ graph [i ] = {"src" : src ,"dst" : dst , "weight" : weight }
50
+
51
+ gsrc = int (input ("\n Enter shortest path source:" ))
52
+ BellmanFord (graph , V , E , gsrc )
You can’t perform that action at this time.
0 commit comments