Skip to content

Instantly share code, notes, and snippets.

@oliviagallucci
Created February 4, 2024 11:49
Show Gist options
  • Save oliviagallucci/920384c965e16632f32f7c84d6915cd4 to your computer and use it in GitHub Desktop.
Save oliviagallucci/920384c965e16632f32f7c84d6915cd4 to your computer and use it in GitHub Desktop.
Example Bellman Ford algorithm in Python
# this program initializes a graph with a given number of vertices,
# adds edges to it, and then executes the bellman-ford algorithm to
# find the shortest paths from a specified source vertex to all
# other vertices in the graph. it also checks for negative weight
# cycles in the graph.
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def print_solution(self, dist):
print("vertex distance from source")
for i in range(self.V):
print("{0}\t\t{1}".format(i, dist[i]))
def bellman_ford(self, src):
dist = [float("Inf")] * self.V
dist[src] = 0
for _ in range(self.V - 1):
for u, v, w in self.graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for u, v, w in self.graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
print("graph contains negative weight cycle")
return
self.print_solution(dist)
if __name__ == "__main__":
g = Graph(5)
g.add_edge(0, 1, -1)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 3)
g.add_edge(1, 3, 2)
g.add_edge(1, 4, 2)
g.add_edge(3, 2, 5)
g.add_edge(3, 1, 1)
g.add_edge(4, 3, -3)
g.bellman_ford(0)
# vertex distance from source
# 0 0
# 1 -1
# 2 2
# 3 -2
# 4 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment