Skip to content

Commit fcde11f

Browse files
authored
Create bellman_ford.py
1 parent 9a32546 commit fcde11f

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

bellman_ford.py

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

0 commit comments

Comments
 (0)