# Bellman Ford Algorithm In Python

Chapter: Python Last Updated: 25-03-2023 18:01:19 UTC

Program:

```            ```/* ............... START ............... */

class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []

self.graph.append([u, v, w])

def bellman_ford(self, src):
# Step 1: Initialize distances from src to all other vertices
# as INFINITE
dist = [float("Inf")] * self.V
dist[src] = 0

# Step 2: Relax all edges |V| - 1 times. A simple shortest
# path from src to any other vertex can have at most |V| - 1
# edges
for i in range(self.V - 1):
# Update dist value and parent index of the adjacent vertices
# of the picked vertex. Consider only those vertices which are
# still in queue
for u, v, w in self.graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
dist[v] = dist[u] + w

# Step 3: Check for negative-weight cycles. The above step
# guarantees shortest distances if graph doesn't contain
# negative weight cycle. If we get a shorter path, then there
# is a cycle
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

# print all distance
for i in range(self.V):
print("Vertex distance from source", i, "is:", dist[i])

# Example usage:
g = Graph(5)
g.bellman_ford(0)

/* ............... END ............... */```
```

Output

```Vertex distance from source 0 is: 0
Vertex distance from source 1 is: -1
Vertex distance from source 2 is: 2
Vertex distance from source 3 is: -2
Vertex distance from source 4 is: 1
This output indicates the shortest distances from the source node 0 to all other nodes in the graph.
For example, the shortest distance from node 0 to node 2 is 2, and the shortest distance from
node 0 to node 3 is -2. Note that the algorithm correctly identifies that the graph does not
contain a negative-weight cycle.```

Notes:

• The Bellman-Ford algorithm is a well-known algorithm for finding the shortest path between nodes in a weighted graph. The algorithm works by iteratively relaxing the edges of the graph, reducing the distance estimate for each node until the shortest path is found. The algorithm also detects negative-weight cycles, which can cause problems for other shortest path algorithms.
• In this Python implementation, the Graph class represents the weighted graph. The class constructor takes the number of vertices in the graph as an argument, and the add_edge method is used to add edges to the graph. The bellman_ford method takes the source node as an argument and uses the Bellman-Ford algorithm to calculate the shortest distances from the source node to all other nodes in the graph.
• The bellman_ford method first initializes an array of distances dist to all nodes as infinite, except for the source node, which is initialized to 0. It then relaxes each edge of the graph V-1 times, where V is the number of vertices in the graph. During each relaxation, the method updates the distance estimate for each node based on the distances of its neighbors. If the updated distance is smaller than the current estimate, the estimate is updated.
• After V-1 rounds of relaxation, the method checks for negative-weight cycles by attempting to relax each edge once more. If any distance estimate can be updated after this final relaxation step, then the graph contains a negative-weight cycle.
• Finally, the method prints the shortest distances from the source node to all other nodes in the graph. If a negative-weight cycle was detected, the method prints a message indicating this.

Tags

#Bellman Ford Algorithm In Python #Bellman Ford algorithm code #Bellman-Ford algorithm example step by step

Similar Programs Chapter Last Updated
Python Program To Find Most Repeated Word In A String Python 23-09-2023
Split String Into Words Python Python 23-09-2023
Remove All Punctuation Python Python 23-09-2023
Python Program To Reverse An Array Python 23-09-2023
Python Program To Find Number Of Palindrome In A String Python 23-09-2023
Python Program To Find Longest Common Substring Python 23-09-2023
Python Program To Find Number Of Days In A Given Month And Year Python 22-09-2023
Python Program To Calculate Age Of A Person Python 22-09-2023
Python Code To Get Day Of Week Python 22-09-2023
Python Convert String To Date Without Time Python 22-09-2023
Python Program To Print Current Date And Time In Format dd/mm/yyyy Python 22-09-2023
Python Program To Find Working Days In A Month Python 19-09-2023
Python Code To Change Date Format Python 16-09-2023
Python Program To Calculate Number Of Days Between Two Dates Python 16-09-2023
Python Program To Calculate Age In Years Months And Days Python 16-09-2023
Python Program To Schedule A Job To Run After A Certain Amount Of Time Python 10-08-2023
Python Program To Schedule A Job To Run Randomly Once A Day Python 10-08-2023
Python Program To Schedule A Job To Run Every Hour Python 10-08-2023
Python Script For Scheduling Jobs Python 09-08-2023
Python String To Datetime Python 23-07-2023
Python Date Comparison Python 23-07-2023
Python Date Now Python 23-07-2023
Python Date to String Python 23-07-2023
How to get file creation and modification date or time in Python Python 19-06-2023
How do you find the difference in time in Python Python 19-06-2023
How To Get The Current Time In Different Time Zones Using Python Python 19-06-2023
Python Get Current Date And Time Python 19-06-2023
Python Program That Schedules A Task To Run At A Specific Time Python 10-06-2023
Python Program To Replace Characters In A String Python 03-06-2023
Python Program To Replace Blank Space With Hyphen Python 30-05-2023

1 2 3 4