Bellman Ford Algorithm (Simple Implementation)
Last Updated :
20 Feb, 2023
We have introduced Bellman Ford and discussed on implementation here.
Input: Graph and a source vertex src
Output: Shortest distance to all vertices from src. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported.
1) This step initializes distances from source to all vertices as infinite and distance to source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.
2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given graph.
.....a) Do following for each edge u-v
..................If dist[v] > dist[u] + weight of edge uv, then update dist[v]
......................dist[v] = dist[u] + weight of edge uv
3) This step reports if there is a negative weight cycle in graph. Do following for each edge u-v
......If dist[v] > dist[u] + weight of edge uv, then "Graph contains negative weight cycle"
The idea of step 3 is, step 2 guarantees shortest distances if graph doesn't contain negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle
Example
Let us understand the algorithm with following example graph. The images are taken from this source.
Let the given source vertex be 0. Initialize all distances as infinite, except the distance to source itself. Total number of vertices in the graph is 5, so all edges must be processed 4 times.

Let all edges are processed in following order: (B, E), (D, B), (B, D), (A, B), (A, C), (D, C), (B, C), (E, D). We get following distances when all edges are processed first time. The first row in shows initial distances. The second row shows distances when edges (B, E), (D, B), (B, D) and (A, B) are processed. The third row shows distances when (A, C) is processed. The fourth row shows when (D, C), (B, C) and (E, D) are processed.

The first iteration guarantees to give all shortest paths which are at most 1 edge long. We get following distances when all edges are processed second time (The last row shows final values).

The second iteration guarantees to give all shortest paths which are at most 2 edges long. The algorithm processes all edges 2 more times. The distances are minimized after the second iteration, so third and fourth iterations don't update the distances.
C++
// A C++ program for Bellman-Ford's single source
// shortest path algorithm.
#include <bits/stdc++.h>
using namespace std;
// The main function that finds shortest
// distances from src to all other vertices
// using Bellman-Ford algorithm. The function
// also detects negative weight cycle
// The row graph[i] represents i-th edge with
// three values u, v and w.
void BellmanFord(int graph[][3], int V, int E,
int src)
{
// Initialize distance of all vertices as infinite.
int dis[V];
for (int i = 0; i < V; i++)
dis[i] = INT_MAX;
// initialize distance of source as 0
dis[src] = 0;
// Relax all edges |V| - 1 times. A simple
// shortest path from src to any other
// vertex can have at-most |V| - 1 edges
for (int i = 0; i < V - 1; i++) {
for (int j = 0; j < E; j++) {
if (dis[graph[j][0]] != INT_MAX && dis[graph[j][0]] + graph[j][2] <
dis[graph[j][1]])
dis[graph[j][1]] =
dis[graph[j][0]] + graph[j][2];
}
}
// 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 (int i = 0; i < E; i++) {
int x = graph[i][0];
int y = graph[i][1];
int weight = graph[i][2];
if (dis[x] != INT_MAX &&
dis[x] + weight < dis[y])
cout << "Graph contains negative"
" weight cycle"
<< endl;
}
cout << "Vertex Distance from Source" << endl;
for (int i = 0; i < V; i++)
cout << i << "\t\t" << dis[i] << endl;
}
// Driver program to test above functions
int main()
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
// Every edge has three values (u, v, w) where
// the edge is from vertex u to v. And weight
// of the edge is w.
int graph[][3] = { { 0, 1, -1 }, { 0, 2, 4 },
{ 1, 2, 3 }, { 1, 3, 2 },
{ 1, 4, 2 }, { 3, 2, 5 },
{ 3, 1, 1 }, { 4, 3, -3 } };
BellmanFord(graph, V, E, 0);
return 0;
}
Java
// A Java program for Bellman-Ford's single source
// shortest path algorithm.
class GFG
{
// The main function that finds shortest
// distances from src to all other vertices
// using Bellman-Ford algorithm. The function
// also detects negative weight cycle
// The row graph[i] represents i-th edge with
// three values u, v and w.
static void BellmanFord(int graph[][], int V, int E,
int src)
{
// Initialize distance of all vertices as infinite.
int []dis = new int[V];
for (int i = 0; i < V; i++)
dis[i] = Integer.MAX_VALUE;
// initialize distance of source as 0
dis[src] = 0;
// Relax all edges |V| - 1 times. A simple
// shortest path from src to any other
// vertex can have at-most |V| - 1 edges
for (int i = 0; i < V - 1; i++)
{
for (int j = 0; j < E; j++)
{
if (dis[graph[j][0]] != Integer.MAX_VALUE && dis[graph[j][0]] + graph[j][2] <
dis[graph[j][1]])
dis[graph[j][1]] =
dis[graph[j][0]] + graph[j][2];
}
}
// 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 (int i = 0; i < E; i++)
{
int x = graph[i][0];
int y = graph[i][1];
int weight = graph[i][2];
if (dis[x] != Integer.MAX_VALUE &&
dis[x] + weight < dis[y])
System.out.println("Graph contains negative"
+" weight cycle");
}
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + "\t\t" + dis[i]);
}
// Driver code
public static void main(String[] args)
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
// Every edge has three values (u, v, w) where
// the edge is from vertex u to v. And weight
// of the edge is w.
int graph[][] = { { 0, 1, -1 }, { 0, 2, 4 },
{ 1, 2, 3 }, { 1, 3, 2 },
{ 1, 4, 2 }, { 3, 2, 5 },
{ 3, 1, 1 }, { 4, 3, -3 } };
BellmanFord(graph, V, E, 0);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program for Bellman-Ford's
# single source shortest path algorithm.
from sys import maxsize
# The main function that finds shortest
# distances from src to all other vertices
# using Bellman-Ford algorithm. The function
# also detects negative weight cycle
# The row graph[i] represents i-th edge with
# three values u, v and w.
def BellmanFord(graph, V, E, src):
# Initialize distance of all vertices as infinite.
dis = [maxsize] * V
# initialize distance of source as 0
dis[src] = 0
# 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(V - 1):
for j in range(E):
if dis[graph[j][0]] + \
graph[j][2] < dis[graph[j][1]]:
dis[graph[j][1]] = dis[graph[j][0]] + \
graph[j][2]
# 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 i in range(E):
x = graph[i][0]
y = graph[i][1]
weight = graph[i][2]
if dis[x] != maxsize and dis[x] + \
weight < dis[y]:
print("Graph contains negative weight cycle")
print("Vertex Distance from Source")
for i in range(V):
print("%d\t\t%d" % (i, dis[i]))
# Driver Code
if __name__ == "__main__":
V = 5 # Number of vertices in graph
E = 8 # Number of edges in graph
# Every edge has three values (u, v, w) where
# the edge is from vertex u to v. And weight
# of the edge is w.
graph = [[0, 1, -1], [0, 2, 4], [1, 2, 3],
[1, 3, 2], [1, 4, 2], [3, 2, 5],
[3, 1, 1], [4, 3, -3]]
BellmanFord(graph, V, E, 0)
# This code is contributed by
# sanjeev2552
C#
// C# program for Bellman-Ford's single source
// shortest path algorithm.
using System;
class GFG
{
// The main function that finds shortest
// distances from src to all other vertices
// using Bellman-Ford algorithm. The function
// also detects negative weight cycle
// The row graph[i] represents i-th edge with
// three values u, v and w.
static void BellmanFord(int [,]graph, int V,
int E, int src)
{
// Initialize distance of all vertices as infinite.
int []dis = new int[V];
for (int i = 0; i < V; i++)
dis[i] = int.MaxValue;
// initialize distance of source as 0
dis[src] = 0;
// Relax all edges |V| - 1 times. A simple
// shortest path from src to any other
// vertex can have at-most |V| - 1 edges
for (int i = 0; i < V - 1; i++)
{
for (int j = 0; j < E; j++)
{
if (dis[graph[j, 0]] = int.MaxValue && dis[graph[j, 0]] + graph[j, 2] <
dis[graph[j, 1]])
dis[graph[j, 1]] =
dis[graph[j, 0]] + graph[j, 2];
}
}
// 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 (int i = 0; i < E; i++)
{
int x = graph[i, 0];
int y = graph[i, 1];
int weight = graph[i, 2];
if (dis[x] != int.MaxValue &&
dis[x] + weight < dis[y])
Console.WriteLine("Graph contains negative" +
" weight cycle");
}
Console.WriteLine("Vertex Distance from Source");
for (int i = 0; i < V; i++)
Console.WriteLine(i + "\t\t" + dis[i]);
}
// Driver code
public static void Main(String[] args)
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
// Every edge has three values (u, v, w) where
// the edge is from vertex u to v. And weight
// of the edge is w.
int [,]graph = {{ 0, 1, -1 }, { 0, 2, 4 },
{ 1, 2, 3 }, { 1, 3, 2 },
{ 1, 4, 2 }, { 3, 2, 5 },
{ 3, 1, 1 }, { 4, 3, -3 }};
BellmanFord(graph, V, E, 0);
}
}
// This code is contributed by Princi Singh
PHP
<?php
// A PHP program for Bellman-Ford's single
// source shortest path algorithm.
// The main function that finds shortest
// distances from src to all other vertices
// using Bellman-Ford algorithm. The function
// also detects negative weight cycle
// The row graph[i] represents i-th edge with
// three values u, v and w.
function BellmanFord($graph, $V, $E, $src)
{
// Initialize distance of all vertices as infinite.
$dis = array();
for ($i = 0; $i < $V; $i++)
$dis[$i] = PHP_INT_MAX;
// initialize distance of source as 0
$dis[$src] = 0;
// 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 = 0; $i < $V - 1; $i++)
{
for ($j = 0; $j < $E; $j++)
{
if ($dis[$graph[$j][0]] != PHP_INT_MAX && $dis[$graph[$j][0]] + $graph[$j][2] <
$dis[$graph[$j][1]])
$dis[$graph[$j][1]] = $dis[$graph[$j][0]] +
$graph[$j][2];
}
}
// 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 ($i = 0; $i < $E; $i++)
{
$x = $graph[$i][0];
$y = $graph[$i][1];
$weight = $graph[$i][2];
if ($dis[$x] != PHP_INT_MAX &&
$dis[$x] + $weight < $dis[$y])
echo "Graph contains negative weight cycle \n";
}
echo "Vertex Distance from Source \n";
for ($i = 0; $i < $V; $i++)
echo $i, "\t\t", $dis[$i], "\n";
}
// Driver Code
$V = 5; // Number of vertices in graph
$E = 8; // Number of edges in graph
// Every edge has three values (u, v, w) where
// the edge is from vertex u to v. And weight
// of the edge is w.
$graph = array( array( 0, 1, -1 ), array( 0, 2, 4 ),
array( 1, 2, 3 ), array( 1, 3, 2 ),
array( 1, 4, 2 ), array( 3, 2, 5),
array( 3, 1, 1), array( 4, 3, -3 ) );
BellmanFord($graph, $V, $E, 0);
// This code is contributed by AnkitRai01
?>
JavaScript
<script>
// Javascript program for Bellman-Ford's single source
// shortest path algorithm.
// The main function that finds shortest
// distances from src to all other vertices
// using Bellman-Ford algorithm. The function
// also detects negative weight cycle
// The row graph[i] represents i-th edge with
// three values u, v and w.
function BellmanFord(graph, V, E, src)
{
// Initialize distance of all vertices as infinite.
var dis = Array(V).fill(1000000000);
// initialize distance of source as 0
dis[src] = 0;
// Relax all edges |V| - 1 times. A simple
// shortest path from src to any other
// vertex can have at-most |V| - 1 edges
for (var i = 0; i < V - 1; i++)
{
for (var j = 0; j < E; j++)
{
if ((dis[graph[j][0]] + graph[j][2]) < dis[graph[j][1]])
dis[graph[j][1]] = dis[graph[j][0]] + graph[j][2];
}
}
// 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 (var i = 0; i < E; i++)
{
var x = graph[i][0];
var y = graph[i][1];
var weight = graph[i][2];
if ((dis[x] != 1000000000) &&
(dis[x] + weight < dis[y]))
document.write("Graph contains negative" +
" weight cycle<br>");
}
document.write("Vertex Distance from Source<br>");
for (var i = 0; i < V; i++)
document.write(i + " " + dis[i] + "<br>");
}
// Driver code
var V = 5; // Number of vertices in graph
var E = 8; // Number of edges in graph
// Every edge has three values (u, v, w) where
// the edge is from vertex u to v. And weight
// of the edge is w.
var graph = [[ 0, 1, -1 ], [ 0, 2, 4 ],
[ 1, 2, 3 ], [ 1, 3, 2 ],
[ 1, 4, 2 ], [ 3, 2, 5 ],
[ 3, 1, 1 ], [ 4, 3, -3 ]];
BellmanFord(graph, V, E, 0);
// This code is contributed by importantly.
</script>
Output: Vertex Distance from Source
0 0
1 -1
2 2
3 -2
4 1
Time Complexity: O(VE)
Space Complexity: O(V)
This implementation is suggested by PrateekGupta10
Similar Reads
Bellman-Ford algorithm in Python
Given a weighted graph with V vertices and E edges, and a source vertex src, find the shortest path from the source vertex to all vertices in the given graph. If a vertex cannot be reached from source vertex, mark its distance as 108.Note: If a graph contains negative weight cycle, return -1.Bellman
3 min read
BellmanâFord Algorithm
Given a weighted graph with V vertices and E edges, along with a source vertex src, the task is to compute the shortest distances from the source to all other vertices. If a vertex is unreachable from the source, its distance should be marked as 108. In the presence of a negative weight cycle, retur
10 min read
Johnsonâs algorithm for All-pairs shortest paths | Implementation
Given a weighted Directed Graph where the weights may be negative, find the shortest path between every pair of vertices in the Graph using Johnson's Algorithm. The detailed explanation of Johnson's algorithm has already been discussed in the previous post. Refer Johnsonâs algorithm for All-pairs
12 min read
Implementation of Wu Manber Algorithm?
What is Wu- Manber Algorithm? The Wu-Manber algorithm is a string-matching algorithm that is used to efficiently search for patterns in a body of text. It is a hybrid algorithm that combines the strengths of the Boyer-Moore and Knuth-Morris-Pratt algorithms to provide fast and accurate pattern match
12 min read
Implementation of Johnsonâs algorithm for all-pairs shortest paths
Johnson's algorithm finds the shortest paths between all pairs of vertices in a weighted directed graph. It allows some of the edge weights to be negative numbers, but no negative-weight cycles may exist. It uses the Bellman-Ford algorithm to re-weight the original graph, removing all negative weigh
14 min read
Peterson's Algorithm for Mutual Exclusion | Set 1 (Basic C implementation)
Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support.Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popu
6 min read
Time and Space Complexity of BellmanâFord Algorithm
The Bellman-Ford algorithm has a time complexity of O(V*E), where V is the number of vertices and E is the number of edges in the graph. In the worst-case scenario, the algorithm needs to iterate through all edges for each vertex, resulting in this time complexity. The space complexity of the Bellma
2 min read
Boothâs Multiplication Algorithm
Booth's algorithm is a multiplication algorithm that multiplies two signed binary numbers in 2's complement notation. Booth used desk calculators that were faster at shifting than adding and created the algorithm to increase their speed. Boothâs algorithm is of interest in the study of computer arch
15 min read
Introduction and implementation of Karger's algorithm for Minimum Cut
Given an undirected and unweighted graph, find the smallest cut (smallest number of edges that disconnects the graph into two components). The input graph may have parallel edges. For example consider the following example, the smallest cut has 2 edges. A Simple Solution use Max-Flow based s-t cut a
15+ min read
Implementation of Non-Restoring Division Algorithm for Unsigned Integer
In the previous article, we have already discussed the Non-Restoring Division Algorithm. In this article, we will discuss the implementation of this algorithm. Non-restoring division algorithm is used to divide two unsigned integers. The other form of this algorithm is Restoring Division. This algor
15 min read