Skip to content

Commit 176c330

Browse files
committed
Add Bellman-Ford Algorithm
1 parent 5d83eb7 commit 176c330

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

data_structures/Graph/BellmanFord.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
def printDist(dist, V):
2+
print("\nVertex 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("\nEdge ",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("\nEnter shortest path source:"))
52+
BellmanFord(graph, V, E, gsrc)

0 commit comments

Comments
 (0)