Skip to content

Commit f62f480

Browse files
authored
Create Bellman Ford's algorithm.py
1 parent 9a5431d commit f62f480

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
class Graph:
3+
4+
def __init__(self, vertices):
5+
self.V = vertices # Total number of vertices in the graph
6+
self.graph = [] # Array of edges
7+
8+
# Add edges
9+
def add_edge(self, s, d, w):
10+
self.graph.append([s, d, w])
11+
12+
# Print the solution
13+
def print_solution(self, dist):
14+
print("Vertex Distance from Source")
15+
for i in range(self.V):
16+
print("{0}\t\t{1}".format(i, dist[i]))
17+
18+
def bellman_ford(self, src):
19+
20+
# Step 1: fill the distance array and predecessor array
21+
dist = [float("Inf")] * self.V
22+
# Mark the source vertex
23+
dist[src] = 0
24+
25+
# Step 2: relax edges |V| - 1 times
26+
for _ in range(self.V - 1):
27+
for s, d, w in self.graph:
28+
if dist[s] != float("Inf") and dist[s] + w < dist[d]:
29+
dist[d] = dist[s] + w
30+
31+
# Step 3: detect negative cycle
32+
# if value changes then we have a negative cycle in the graph
33+
# and we cannot find the shortest distances
34+
for s, d, w in self.graph:
35+
if dist[s] != float("Inf") and dist[s] + w < dist[d]:
36+
print("Graph contains negative weight cycle")
37+
return
38+
39+
# No negative weight cycle found!
40+
# Print the distance and predecessor array
41+
self.print_solution(dist)
42+
43+
44+
g = Graph(5)
45+
g.add_edge(0, 1, 5)
46+
g.add_edge(0, 2, 4)
47+
g.add_edge(1, 3, 3)
48+
g.add_edge(2, 1, 6)
49+
g.add_edge(3, 2, 2)
50+
51+
g.bellman_ford(0)

0 commit comments

Comments
 (0)