From 6a23c14c0d38faa32aa4a3389dc5450cf80b2758 Mon Sep 17 00:00:00 2001 From: Harshdeep Date: Wed, 6 Oct 2021 12:48:05 +0530 Subject: [PATCH] Added Bellman-Ford Algorithm --- Bellman_Ford_Algorithm/Bellman_Ford.py | 53 +++++++++++++++++++ .../Bellman_Ford_Algorithm.md | 4 ++ 2 files changed, 57 insertions(+) create mode 100644 Bellman_Ford_Algorithm/Bellman_Ford.py create mode 100644 Bellman_Ford_Algorithm/Bellman_Ford_Algorithm.md diff --git a/Bellman_Ford_Algorithm/Bellman_Ford.py b/Bellman_Ford_Algorithm/Bellman_Ford.py new file mode 100644 index 0000000..381ed6d --- /dev/null +++ b/Bellman_Ford_Algorithm/Bellman_Ford.py @@ -0,0 +1,53 @@ +# Bellman Ford Algorithm in Python + + +class Graph: + + def __init__(self, vertices): + self.V = vertices # Total number of vertices in the graph + self.graph = [] # Array of edges + + # Add edges + def add_edge(self, s, d, w): + self.graph.append([s, d, w]) + + # Print the solution + 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): + + # Step 1: fill the distance array and predecessor array + dist = [float("Inf")] * self.V + # Mark the source vertex + dist[src] = 0 + + # Step 2: relax edges |V| - 1 times + for _ in range(self.V - 1): + for s, d, w in self.graph: + if dist[s] != float("Inf") and dist[s] + w < dist[d]: + dist[d] = dist[s] + w + + # Step 3: detect negative cycle + # if value changes then we have a negative cycle in the graph + # and we cannot find the shortest distances + for s, d, w in self.graph: + if dist[s] != float("Inf") and dist[s] + w < dist[d]: + print("Graph contains negative weight cycle") + return + + # No negative weight cycle found! + # Print the distance and predecessor array + self.print_solution(dist) + + +g = Graph(5) +g.add_edge(0, 1, 5) +g.add_edge(0, 2, 4) +g.add_edge(1, 3, 3) +g.add_edge(2, 1, 6) +g.add_edge(3, 2, 2) + +g.bellman_ford(0) \ No newline at end of file diff --git a/Bellman_Ford_Algorithm/Bellman_Ford_Algorithm.md b/Bellman_Ford_Algorithm/Bellman_Ford_Algorithm.md new file mode 100644 index 0000000..1c53b15 --- /dev/null +++ b/Bellman_Ford_Algorithm/Bellman_Ford_Algorithm.md @@ -0,0 +1,4 @@ +# BELLMAN FORD ALGORITHM + + +Bellman Ford algorithm helps us find the shortest path from a vertex to all other vertices of a weighted graph. \ No newline at end of file