ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.1 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm |
| Last Crawled | 2026-04-15 23:21:15 (1 day ago) |
| First Indexed | 2023-06-19 14:37:50 (2 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Bellman Ford’s Algorithm in Data Structures - Working, Example and Applications |
| Meta Description | Explore Bellman Ford’s Algorithm in Data Structures: Understand its working principles and versatile applications for efficient path finding. |
| Meta Canonical | null |
| Boilerpipe Text | The Bellman-Ford Algorithm is an algorithm that computes shortest paths in a directed graph. This algorithm can help you understand the implications of multiple connections and how they determine efficient travel routes or optimal cost networks.
In this
DSA tutorial
, we will explore the Bellman-Ford Algorithm to get a better understanding of its basic principles and practical applications. What is the difference between Dijkstra and Bellman-Ford algorithm?.
By 2027, 80% of coding interviews will focus on DSA skills. Ace them with our
Free Data Structures and Algorithms Course
today!
What is Bellman Ford's Algorithm in Data Structures?
Bellman-Ford algorithm is used to calculate the
shortest paths
from a single source vertex to all vertices in the graph.Â
This algorithm even works on graphs with a negative edge weight cycle i.e. a cycle of edges with the sum of weights equal to a negative number. This algorithm follows the bottom-up approach.
At its core, the algorithm works by building up a set of "distance estimates" for each node in a graph, gradually refining them until every node has the best possible estimate. While the algorithm may seem complex at first glance, its ability to solve a wide variety of problems has made it a crucial tool for many fields, from computer science to civil engineering.
Bellman Ford's Algorithm Example
Here's an example of the bellman ford's algorithm in action:
Let's consider a directed weighted graph with the following edges and their respective weights:
Edge 1: A -> B, weight = 2
Edge 2: A -> C, weight = 4
Edge 3: B -> C, weight = 1
Edge 4: B -> D, weight = 7
Edge 5: C -> D, weight = 3
Edge 6: D -> A, weight = 5
We want to find the shortest paths from a source vertex (let's say A) to all other vertices in the graph.
Step 1: Initialization
We set the distance to the source vertex as 0, and all other distances as infinity.
Distance to A: 0
Distance to B: Infinity
Distance to C: Infinity
Distance to D: Infinity
Step 2: Relaxation
We iterate over all the edges |V| - 1 time, where |V| is the number of vertices in the graph, and relax the edges. In each iteration, we update the distances if we find a shorter path.
Iteration 1:
Distance to A: 0
Distance to B: 2
Distance to C: 4
Distance to D: Infinity
Iteration 2:
Distance to A: 0
Distance to B: 2
Distance to C: 3
Distance to D: 6
Iteration 3:
Distance to A: 0
Distance to B: 2
Distance to C: 3
Distance to D: 6
Iteration 4:
Distance to A: 0
Distance to B: 2
Distance to C: 3
Distance to D: 6
Iteration 5:
Distance to A: 0
Distance to B: 2
Distance to C: 3
Distance to D: 6
Step 3: Negative cycle detection
After |V| - 1 iterations, we check for any negative cycles in the graph. In this example, there are no negative cycles.
Step 4: Result
The final distances from the source vertex A to all other vertices are as follows:
Distance to A: 0
Distance to B: 2
Distance to C: 3
Distance to D: 6
So, the shortest path from A to B is 2, from A to C is 3, and from A to D is 6.
Read More -
Data Structure Interview Questions and Answers
How Bellman Ford's Algorithm Works?
Bellman-Ford's algorithm is a shortest path algorithm used to find the shortest paths from a source vertex to all other vertices in a weighted directed graph. It can handle graphs with negative edge weights, unlike Dijkstra's algorithm, which requires non-negative weights. The algorithm works as follows:
Initialize the distance values for all vertices in the graph as infinity, except for the source vertex, which is set to 0. Also, initialize the predecessor of all vertices as undefined.
Relaxation step: Repeat the following process |V|-1 times, where |V| is the number of vertices in the graph.
For each edge (u, v) in the graph, where u is the source vertex and v is the destination vertex:
If the distance from the source vertex to u plus the weight of the edge (u, v) is less than the current distance value of v, update the distance of v with this new value.
Also, update the predecessor of v as u.
Check for negative-weight cycles:
Repeat the following process for each edge (u, v) in the graph.
If the distance from the source vertex to u plus the weight of the edge (u, v) is less than the current distance value of v, then there is a negative-weight cycle in the graph.
After completing the relaxation step |V|-1 times, the algorithm will have calculated the shortest distances from the source vertex to all other vertices in the graph (if no negative-weight cycles exist). If there is a negative-weight cycle, step 3 will detect it.
If required, the shortest paths can be reconstructed using the predecessor information. Starting from the destination vertex, follow the predecessor pointers until reaching the source vertex to obtain the shortest path.
The algorithm guarantees the correct shortest path distances if there are no negative-weight cycles reachable from the source vertex. However, if there is a negative-weight cycle that can be reached from the source vertex, the algorithm will detect it in step 3. In such cases, the algorithm cannot provide meaningful shortest path distances, as the negative-weight cycle allows for infinite negative weight reductions
Bellman Ford's Algorithm Pseudocode
Bellman Ford's algorithm, is used to find the shortest paths from a single source vertex to all other vertices in a weighted directed graph. The algorithm can handle negative edge weights but detects negative cycles.
function
BellmanFord
(Graph, source)
:
// Step 1: Initialization
for
each vertex v in Graph:
distance[v] := infinity
predecessor[v] :=
null
distance[source] :=
0
// Step 2: Relaxation
for
i from
1
to |V|-
1
:
for
each
edge
(u, v)
in Graph:
if
distance[u] + weight(u, v) < distance[v]:
distance[v] := distance[u] + weight(u, v)
predecessor[v] := u
// Step 3: Check for negative cycles
for
each
edge
(u, v)
in Graph:
if
distance[u] + weight(u, v) < distance[v]:
return
"Graph contains a negative cycle"
// Step 4: Output the shortest paths
return
distance[], predecessor[]
In this pseudocode:
The graph
represents the input graph.
The source
is the source vertex from which to find the shortest paths.
distance[v]
represents the shortest distance from the source to vertex v.
predecessor[v]
stores the predecessor of vertex v in the shortest path.
The algorithm consists of four main steps:
Initialization:
Set the distance of all vertices to infinity, except for the source vertex, which is set to 0. Set the predecessor of all vertices to null.
Relaxation:
Perform a relaxation step for each edge in the graph |V|-1 times. The relaxation step updates the distance to each vertex v if there exists a shorter path through vertex u.
Check for negative cycles:
Perform one more iteration to check for negative cycles. If a shorter path can still be found, then there exists a negative cycle in the graph.
Output the shortest paths:
After completing the algorithm, the shortest distances and predecessors are returned.
Note that |V| represents the number of vertices in the graph, and weight(u, v) returns the weight/cost of the edge (u, v).
Implementation of Bellman Ford’s Algorithm
Python
Java
C++
class
Graph
:
def
__init__
(
self, vertices
):
self.V = vertices
# No. of vertices
self.graph = []
# function to add an edge to graph
def
addEdge
(
self, u, v, w
):
self.graph.append([u, v, w])
# utility function used to print the solution
def
printArr
(
self, dist
):
print
(
"Vertex Distance from Source"
)
for
i
in
range
(self.V):
print
(
"{0}\t\t{1}"
.
format
(i, dist[i]))
# The main function that finds shortest distances from src to
# all other vertices using Bellman-Ford algorithm. The function
# also detects negative weight cycle
def
BellmanFord
(
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
_
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
self.printArr(dist)
# Driver's code
if
__name__ ==
'__main__'
:
g = Graph(
5
)
g.addEdge(
0
,
1
, -
1
)
g.addEdge(
0
,
2
,
4
)
g.addEdge(
1
,
2
,
3
)
g.addEdge(
1
,
3
,
2
)
g.addEdge(
1
,
4
,
2
)
g.addEdge(
3
,
2
,
5
)
g.addEdge(
3
,
1
,
1
)
g.addEdge(
4
,
3
, -
3
)
# function call
g.BellmanFord(
0
)
import
java.io.*;
import
java.lang.*;
import
java.util.*;
// A class to represent a connected, directed and weighted
// graph
class
Graph
{
// A class to represent a weighted edge in graph
class
Edge
{
int
src, dest, weight;
Edge() { src = dest = weight =
0
; }
};
int
V, E;
Edge edge[];
// Creates a graph with V vertices and E edges
Graph(
int
v,
int
e)
{
V = v;
E = e;
edge =
new
Edge
[e];
for
(
int
i
=
0
; i < e; ++i)
edge[i] =
new
Edge
();
}
// The main function that finds shortest distances from
// src to all other vertices using Bellman-Ford
// algorithm. The function also detects negative weight
// cycle
void
BellmanFord
(Graph graph,
int
src)
{
int
V
=
graph.V, E = graph.E;
int
dist[] =
new
int
[V];
// Step 1: Initialize distances from src to all
// other vertices as INFINITE
for
(
int
i
=
0
; i < V; ++i)
dist[i] = Integer.MAX_VALUE;
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
(
int
i
=
1
; i < V; ++i) {
for
(
int
j
=
0
; j < E; ++j) {
int
u
=
graph.edge[j].src;
int
v
=
graph.edge[j].dest;
int
weight
=
graph.edge[j].weight;
if
(dist[u] != Integer.MAX_VALUE
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// 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
(
int
j
=
0
; j < E; ++j) {
int
u
=
graph.edge[j].src;
int
v
=
graph.edge[j].dest;
int
weight
=
graph.edge[j].weight;
if
(dist[u] != Integer.MAX_VALUE
&& dist[u] + weight < dist[v]) {
System.out.println(
"Graph contains negative weight cycle"
);
return
;
}
}
printArr(dist, V);
}
// A utility function used to print the solution
void
printArr
(
int
dist[],
int
V)
{
System.out.println(
"Vertex Distance from Source"
);
for
(
int
i
=
0
; i < V; ++i)
System.out.println(i +
"\t\t"
+ dist[i]);
}
// Driver's code
public
static
void
main
(String[] args)
{
int
V
=
5
;
// Number of vertices in graph
int
E
=
8
;
// Number of edges in graph
Graph
graph
=
new
Graph
(V, E);
// add edge 0-1 (or A-B in above figure)
graph.edge[
0
].src =
0
;
graph.edge[
0
].dest =
1
;
graph.edge[
0
].weight = -
1
;
// add edge 0-2 (or A-C in above figure)
graph.edge[
1
].src =
0
;
graph.edge[
1
].dest =
2
;
graph.edge[
1
].weight =
4
;
// add edge 1-2 (or B-C in above figure)
graph.edge[
2
].src =
1
;
graph.edge[
2
].dest =
2
;
graph.edge[
2
].weight =
3
;
// add edge 1-3 (or B-D in above figure)
graph.edge[
3
].src =
1
;
graph.edge[
3
].dest =
3
;
graph.edge[
3
].weight =
2
;
// add edge 1-4 (or B-E in above figure)
graph.edge[
4
].src =
1
;
graph.edge[
4
].dest =
4
;
graph.edge[
4
].weight =
2
;
// add edge 3-2 (or D-C in above figure)
graph.edge[
5
].src =
3
;
graph.edge[
5
].dest =
2
;
graph.edge[
5
].weight =
5
;
// add edge 3-1 (or D-B in above figure)
graph.edge[
6
].src =
3
;
graph.edge[
6
].dest =
1
;
graph.edge[
6
].weight =
1
;
// add edge 4-3 (or E-D in above figure)
graph.edge[
7
].src =
4
;
graph.edge[
7
].dest =
3
;
graph.edge[
7
].weight = -
3
;
// Function call
graph.BellmanFord(graph,
0
);
}
}
#
include
<iostream>
using
namespace
std;
// a structure to represent a weighted edge in graph
struct
Edge
{
int
src, dest, weight;
};
// a structure to represent a connected, directed and
// weighted graph
struct
Graph
{
// V-> Number of vertices, E-> Number of edges
int
V, E;
// graph is represented as an array of edges.
struct
Edge
* edge;
};
// Creates a graph with V vertices and E edges
struct
Graph
*
createGraph
(
int
V,
int
E)
{
struct
Graph
* graph =
new
Graph;
graph->V = V;
graph->E = E;
graph->edge =
new
Edge[E];
return
graph;
}
// A utility function used to print the solution
void
printArr
(
int
dist[],
int
n)
{
printf
(
"Vertex Distance from Source\n"
);
for
(
int
i =
0
; i < n; ++i)
printf
(
"%d \t\t %d\n"
, i, dist[i]);
}
// The main function that finds shortest distances from src
// to all other vertices using Bellman-Ford algorithm. The
// function also detects negative weight cycle
void
BellmanFord
(
struct
Graph* graph,
int
src)
{
int
V = graph->V;
int
E = graph->E;
int
dist[V];
// Step 1: Initialize distances from src to all other
// vertices as INFINITE
for
(
int
i =
0
; i < V; i++)
dist[i] = INT_MAX;
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
(
int
i =
1
; i <= V -
1
; i++) {
for
(
int
j =
0
; j < E; j++) {
int
u = graph->edge[j].src;
int
v = graph->edge[j].dest;
int
weight = graph->edge[j].weight;
if
(dist[u] != INT_MAX
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// 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
(
int
i =
0
; i < E; i++) {
int
u = graph->edge[i].src;
int
v = graph->edge[i].dest;
int
weight = graph->edge[i].weight;
if
(dist[u] != INT_MAX
&& dist[u] + weight < dist[v]) {
printf
(
"Graph contains negative weight cycle"
);
return
;
// If negative cycle is detected, simply
// return
}
}
printArr
(dist, V);
return
;
}
// Driver's code
int
main
()
{
/* Let us create the graph given in above example */
int
V =
5
;
// Number of vertices in graph
int
E =
8
;
// Number of edges in graph
struct
Graph
* graph =
createGraph
(V, E);
// add edge 0-1 (or A-B in above figure)
graph->edge[
0
].src =
0
;
graph->edge[
0
].dest =
1
;
graph->edge[
0
].weight =
-1
;
// add edge 0-2 (or A-C in above figure)
graph->edge[
1
].src =
0
;
graph->edge[
1
].dest =
2
;
graph->edge[
1
].weight =
4
;
// add edge 1-2 (or B-C in above figure)
graph->edge[
2
].src =
1
;
graph->edge[
2
].dest =
2
;
graph->edge[
2
].weight =
3
;
// add edge 1-3 (or B-D in above figure)
graph->edge[
3
].src =
1
;
graph->edge[
3
].dest =
3
;
graph->edge[
3
].weight =
2
;
// add edge 1-4 (or B-E in above figure)
graph->edge[
4
].src =
1
;
graph->edge[
4
].dest =
4
;
graph->edge[
4
].weight =
2
;
// add edge 3-2 (or D-C in above figure)
graph->edge[
5
].src =
3
;
graph->edge[
5
].dest =
2
;
graph->edge[
5
].weight =
5
;
// add edge 3-1 (or D-B in above figure)
graph->edge[
6
].src =
3
;
graph->edge[
6
].dest =
1
;
graph->edge[
6
].weight =
1
;
// add edge 4-3 (or E-D in above figure)
graph->edge[
7
].src =
4
;
graph->edge[
7
].dest =
3
;
graph->edge[
7
].weight =
-3
;
// Function call
BellmanFord
(graph,
0
);
return
0
;
}
Output
Vertex Distance from Source
0
0
1
-
1
2
2
3
-
2
4
1
Applications of Bellman Ford's Algorithm
Routing protocols:
The Bellman-Ford algorithm is widely used in computer networks as the basis for distance-vector routing protocols. These protocols are responsible for determining the best path for data packets to travel through a network. Examples of routing protocols that use the Bellman-Ford algorithm include the Routing Information Protocol (RIP) and the Border Gateway Protocol (BGP).
Network topology analysis:
The Bellman-Ford algorithm can be used to analyze and understand the topology of a network. By running the algorithm on a network graph, it can determine the shortest path and associated costs between different nodes. This information is valuable for network administrators to optimize network performance and identify potential bottlenecks.
Internet Service Providers (ISPs):
ISPs use the Bellman-Ford algorithm for network traffic engineering and to ensure efficient routing of data across their networks. By applying the algorithm to the network topology, ISPs can determine the best path for data packets to reach their destination, considering factors such as link capacities, congestion, and network policies.
Distance vector protocols in wireless sensor networks:
Wireless sensor networks often have limited resources, such as battery power and computing capabilities. The Bellman-Ford algorithm can be implemented in these networks to compute the shortest path while considering energy constraints and other network-specific requirements.
Virtual Private Networks (VPNs):
The Bellman-Ford algorithm is used in VPNs to determine the optimal path for network traffic between different nodes in the VPN infrastructure. It helps establish secure and efficient communication between geographically distributed networks.
Resource allocation in cloud computing:
The Bellman-Ford algorithm can be used to allocate resources in cloud computing environments. By modeling the cloud infrastructure as a graph, the algorithm can find the shortest path and associated costs between different resources, such as servers, storage, and network components. This information can assist in optimizing resource allocation and load balancing.
Complexity Analysis of Bellman Ford's Algorithm
Time Complexity
Case
Time Complexity
Best Case
O(E)
Average Case
O(VE)
Worst Case
O(VE)
Space Complexity:
The
space complexity
of Bellman Ford's Algorithm is
O(V)
.
Summary
The Bellman-Ford Algorithm is a fundamental algorithm used to find the shortest paths in a graph, considering the weights or costs associated with each edge. It is commonly used in computer networks and routing protocols. Overall, the Bellman-Ford Algorithm is a versatile and widely used algorithm for solving shortest-path problems in various domains, enabling efficient routing and resource allocation in networks.Â
Average Java Solution Architect earns ₹35–45 LPA. Don’t let your career stall at ₹8–10 LPA—Enroll now in our
Java Architect Course
to fast-track your growth.
FAQs
The worst-case time complexity of Bellman Ford's Algorithm is O(VE).
Routing Information Protocol (RIP) and the Border Gateway Protocol (BGP) are some routing protocols that use the Bellman-Ford's Algorithm
The Bellman Ford's algorithm consists of four main steps.
Take our Datastructures skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.
GET FREE CHALLENGE |
| Markdown | [ScholarHat](https://www.scholarhat.com/)
[Live Training]()
[All Live Trainings](https://www.scholarhat.com/training)
### Training Categories
 .NET Platform
 AI/ML & Gen AI
 Career & Leadership
 Cloud & DevOps
 Java Platform
 JS & Front-end
### Category Name
Live sessions with industry experts
[ .NET AI & ML Engineer Certification Training Build Intelligent AI/ML-Driven Solutions with ML.NET](https://www.scholarhat.com/training/net-ai-ml-certification-training)
[ .NET Certification Training Master C\# & SQL Server from basic to advanced](https://www.scholarhat.com/training/net-certification-training)
[ .NET Microservices Certification Training Build scalable microservices using .NET & Docker/K8s](https://www.scholarhat.com/training/net-microservices-certification-training)
[ .NET Software Architecture and Design Training Design clean, maintainable, enterprise-grade architectures](https://www.scholarhat.com/training/software-architecture-design-training)
[ ASP.NET Core Certification Training Build fast web apps using ASP.NET Core, EF & Web API](https://www.scholarhat.com/training/aspnet-core-certification-training)
[ Blazor Certification Training Build interactive web apps using C\# & Razor](https://www.scholarhat.com/training/blazor-certification-training)
#### Join Live Sessions
Learn with experts in real-time
[Join Now](https://www.scholarhat.com/training/batches)
[Job-Ready Tracks]()
[All Job-Ready Tracks](https://www.scholarhat.com/job-oriented)
### Training Categories
 .NET
 AI/ML
 Java
### .NET
Roles-based Live training programs
[ .NET & Azure Solution Architect Program Master Azure, System Design & Microservices Architecture](https://www.scholarhat.com/job-oriented/net-azure-solution-architect-certification-training)
[ AI-Driven .NET Tech Lead Program Master ASP.NET Core, Angular/React, AI/ML with Azure](https://www.scholarhat.com/job-oriented/net-tech-lead-certification-training)
[ AI-Powered Full-Stack .NET Developer Program Master AI, ASP.NET Core with Angular or React](https://www.scholarhat.com/job-oriented/full-stack-net-developer-certification-training)
#### Start Your Career
Job-ready tracks
[Explore](https://www.scholarhat.com/training/batches)
[LIVE Batches](https://www.scholarhat.com/training/batches) [FREE Masterclasses](https://www.scholarhat.com/master-classes)
[FREE Courses/Books]()
[Free Courses](https://www.scholarhat.com/free-course)
[Free Books](https://www.scholarhat.com/books)
[Skill Tests](https://www.scholarhat.com/skill-tests)
[Sandboxes]()
[Cloud Sandboxes](https://www.scholarhat.com/sandbox)
[Practice DSA](https://www.scholarhat.com/problems)
[Explore]()
[Membership](https://www.scholarhat.com/membership/live)
[Online Compiler](https://www.scholarhat.com/compiler)
[Skill Tests](https://www.scholarhat.com/skill-tests)
[Tutorial](https://www.scholarhat.com/tutorial)
[Reviews](https://www.scholarhat.com/reviews)
[0](https://www.scholarhat.com/cart)
[Login/SignUp](https://www.scholarhat.com/login)
Live Training
 .NET Platform
 AI/ML & Gen AI
 Career & Leadership
 Cloud & DevOps
 Java Platform
 JS & Front-end
[All Live Trainings](https://www.scholarhat.com/training)
Job Ready Tracks
 .NET
 AI/ML
 Java
[All Job-Ready Tracks](https://www.scholarhat.com/job-oriented)
[Free Master Classes](https://www.scholarhat.com/master-classes)
Free Courses / Books
[Free Courses](https://www.scholarhat.com/free-course)
[Free Books](https://www.scholarhat.com/books)
[Skill Assessments](https://www.scholarhat.com/skill-tests)
Sandboxes
[Cloud Sandboxes](https://www.scholarhat.com/sandbox)
[Practice DSA](https://www.scholarhat.com/problems)
[Training Batches](https://www.scholarhat.com/training/batches)
Explore
[Membership](https://www.scholarhat.com/membership/live)
[DSA Problems](https://www.scholarhat.com/problems)
[Online Compiler](https://www.scholarhat.com/compiler)
[Skill Assessments](https://www.scholarhat.com/skill-tests)
[Reviews](https://www.scholarhat.com/Reviews)
[Tutorials](https://www.scholarhat.com/tutorial)
[Login/SignUp](https://www.scholarhat.com/login)
[Live Batches](https://www.scholarhat.com/training/batches)
[Masterclasses](https://www.scholarhat.com/master-classes)
Menu
[Free Courses](https://www.scholarhat.com/free-course)
Account
[Login / Sign Up](https://www.scholarhat.com/Account/Login)
Toggle Theme
Browse Tutorials
## [problems]()
[Radix Sort for Strings Beginners 4 min](https://www.scholarhat.com/tutorial/datastructures/radix-sort "Get More Details")
[Mostly Asked DSA Interview Practice Questions Beginners 6 min](https://www.scholarhat.com/tutorial/datastructures/dsa-interview-practice "Get More Details")
[Maximum Subarray Sum Problem Beginners 3 min](https://www.scholarhat.com/tutorial/datastructures/maximum-subarray-sum-problem "Get More Details")
[Merge Sorted Arrays Beginners 4 min](https://www.scholarhat.com/tutorial/datastructures/merge-sorted-arrays "Get More Details")
[Linear Search with Duplicates Beginners 4 min](https://www.scholarhat.com/tutorial/datastructures/linear-search-with-duplicates "Get More Details")
[Quick Sort with Pivot Selection Beginners 4 min](https://www.scholarhat.com/tutorial/datastructures/quick-sort-with-pivot-selection "Get More Details")
[Insertion Sort for Nearly Sorted Array Beginners 4 min](https://www.scholarhat.com/tutorial/datastructures/insertion-sort-for-nearly-sorted-arrays "Get More Details")
[Two Sum Problem Beginners 3 min](https://www.scholarhat.com/tutorial/datastructures/two-sum-problem "Get More Details")
[Selection Sort Algorithm Beginners 3 min](https://www.scholarhat.com/tutorial/datastructures/selection-sort-algorithm "Get More Details")
[Bubble Sort Algorithm Beginners 4 min](https://www.scholarhat.com/tutorial/datastructures/bubble-sort-algorithm "Get More Details")
[0/1 Knapsack Problem Beginners 5 min](https://www.scholarhat.com/tutorial/datastructures/knapsack-problem "Get More Details")
[Bellman Ford’s Algorithm in Data Structures - Working, Example and Applications Advanced 32 min](https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm "Get More Details")
## [Non Linear]()
[Introduction to Non-linear Data Structures Beginners 42 min](https://www.scholarhat.com/tutorial/datastructures/non-linear-data-structure "Get More Details")
## [Comparisons]()
[Differences Between Stack and Queue Data Structures Beginners 9 min](https://www.scholarhat.com/tutorial/datastructures/stack-vs-queue "Get More Details")
[Breadth First Search vs Depth First Search Beginners 7 min](https://www.scholarhat.com/tutorial/datastructures/bfs-vs-dfs "Get More Details")
## [Abstract]()
[Abstract Data Type in Data Structures With Example Beginners 56 min](https://www.scholarhat.com/tutorial/datastructures/abstract-data-type "Get More Details")
## [Binary Tree]()
[Singly Binary Tree Traversal: Data Structure Beginners 25 min](https://www.scholarhat.com/tutorial/datastructures/singly-binary-tree-traversal-in-data-structures "Get More Details")
[Binary Tree Array Implementation Beginners 25 min](https://www.scholarhat.com/tutorial/datastructures/binary-tree-array-implementation "Get More Details")
[Binary Trees in Data Structures - Types, Implementation, Applications Intermediate 25 min](https://www.scholarhat.com/tutorial/datastructures/binary-tree-in-data-structures "Get More Details")
## [Basics]()
[DSA Examples: A-Z Guide Beginners 12 min](https://www.scholarhat.com/tutorial/datastructures/data-structures-examples "Get More Details")
[Data Structures and Algorithms Beginners 12 min](https://www.scholarhat.com/tutorial/datastructures/data-structures-algorithms-real-life-examples-of-algorithms "Get More Details")
## [Queue]()
[Deque in Data Structures Beginners 23 min](https://www.scholarhat.com/tutorial/datastructures/deque-in-data-structures "Get More Details")
[What is a Priority Queue Data Structure? Implementation, Type & Many More Beginners 113 min](https://www.scholarhat.com/tutorial/datastructures/priority-queue-in-data-structures "Get More Details")
[Implementing Circular Queue in Data Structures Beginners 9 min](https://www.scholarhat.com/tutorial/datastructures/circular-queue-in-data-structures "Get More Details")
[Queue in Data Structures - Types & Algorithm (With Example) Beginners 71 min](https://www.scholarhat.com/tutorial/datastructures/queue-data-structure-implementation "Get More Details")
## [Tree]()
[Understanding Trie Data Structure Beginners 17 min](https://www.scholarhat.com/tutorial/datastructures/trie-data-structure "Get More Details")
[Spanning Tree and Minimum Spanning Tree in Data Structures - Kruskal's and Prim's Algorithms Advanced 49 min](https://www.scholarhat.com/tutorial/datastructures/spanning-tree-in-data-structures "Get More Details")
[AVL Tree in Data Structures with Examples Advanced 43 min](https://www.scholarhat.com/tutorial/datastructures/avl-tree-in-data-structures "Get More Details")
[Trees in Data Structures - Its Structure, Operations & Applications Advanced 55 min](https://www.scholarhat.com/tutorial/datastructures/trees-in-data-structures "Get More Details")
[Segment Tree in Data Structures: Operations, Advantages and Disadvantages Advanced 43 min](https://www.scholarhat.com/tutorial/datastructures/segment-tree-in-data-strustures "Get More Details")
[K-Dimensional Tree in Data Structures Advanced 21 min](https://www.scholarhat.com/tutorial/datastructures/k-dimentional-tree-in-data-structures "Get More Details")
## [Linked List]()
[Singly Linked List in Data Structure Beginners 12 min](https://www.scholarhat.com/tutorial/datastructures/singly-linked-list-in-data-structure "Get More Details")
[Reverse Linked List Beginners 5 min](https://www.scholarhat.com/tutorial/datastructures/reverse-linked-list "Get More Details")
[Linked List in Data Structures - Types of Linked Lists & Its Applications Beginners 32 min](https://www.scholarhat.com/tutorial/datastructures/linkedlist-in-data-structures "Get More Details")
[Doubly Linked List in Data Structures with Examples Beginners 114 min](https://www.scholarhat.com/tutorial/datastructures/doubly-linked-list-in-data-structures "Get More Details")
[Circular Linked Lists in Data Structures Intermediate 69 min](https://www.scholarhat.com/tutorial/datastructures/circular-linked-list-in-data-structures "Get More Details")
## [Sorting Algorithms]()
[Dijkstra’s Algorithm in Data Structures Beginners 9 min](https://www.scholarhat.com/tutorial/datastructures/dijkstras-algorithm "Get More Details")
[Binary Search in Data Structures Intermediate 25 min](https://www.scholarhat.com/tutorial/datastructures/binary-search-in-data-structures "Get More Details")
[Data Structures Sorting: Types and Examples Explained Intermediate 11 min](https://www.scholarhat.com/tutorial/datastructures/sorting-in-data-structures "Get More Details")
[Bubble Sort in Data Structures Intermediate 24 min](https://www.scholarhat.com/tutorial/datastructures/bubble-sort-in-data-structures "Get More Details")
[Selection Sort in Data Structures Intermediate 18 min](https://www.scholarhat.com/tutorial/datastructures/selection-sort-in-data-structures "Get More Details")
[Insertion Sort in Data Structures - Algorithm, Working, & Advantages Intermediate 16 min](https://www.scholarhat.com/tutorial/datastructures/insertion-sort-in-data-structures "Get More Details")
[Merge Sort in Data Structures and Algorithms: With Implementation in C++/Java/Python Intermediate 23 min](https://www.scholarhat.com/tutorial/datastructures/merge-sort-in-data-structures "Get More Details")
[Counting Sort in Data Structures Intermediate 16 min](https://www.scholarhat.com/tutorial/datastructures/counting-sort-in-data-structures "Get More Details")
[Radix Sort in Data Structures - Its Algorithm, Working, & Complexity Intermediate 20 min](https://www.scholarhat.com/tutorial/datastructures/radix-sort-in-data-structures "Get More Details")
[Bucket Sort in Data Structures Intermediate 24 min](https://www.scholarhat.com/tutorial/datastructures/bucket-sort-in-data-structures "Get More Details")
[Shell Sort in Data Structures - Algorithm, Visualization, & Complexity Intermediate 17 min](https://www.scholarhat.com/tutorial/datastructures/shell-sort-in-data-structures "Get More Details")
[Heap Sort Algorithm in Data Structures - Its Working, Implementation & Applications Advanced 27 min](https://www.scholarhat.com/tutorial/datastructures/heap-sort-in-data-structures "Get More Details")
[Tower of Hanoi in Data Structures Advanced 31 min](https://www.scholarhat.com/tutorial/datastructures/tower-of-hanoi-in-data-structures "Get More Details")
## [sorts & algorithms]()
[Counting Sort for Limited Range Beginners 5 min](https://www.scholarhat.com/tutorial/datastructures/counting-sort "Get More Details")
## [Binary Search]()
[Binary Search in Rotated Sorted Array Beginners 5 min](https://www.scholarhat.com/tutorial/datastructures/binary-search "Get More Details")
[In-order Traversal of Binary Search Tree Beginners 5 min](https://www.scholarhat.com/tutorial/datastructures/traversal-of-binary-serach-tree "Get More Details")
[Binary Search Tree in Data Structures Intermediate 31 min](https://www.scholarhat.com/tutorial/datastructures/binary-search-tree-in-data-structures "Get More Details")
## [Sorting Algorithm]()
[Merge Sort for Linked List Beginners 7 min](https://www.scholarhat.com/tutorial/datastructures/merge-sort-for-linked-list "Get More Details")
[Quick Sort Algorithm in Data Structures - Its Types ( With Examples ) Intermediate 23 min](https://www.scholarhat.com/tutorial/datastructures/quick-sort-in-data-structures "Get More Details")
[Greedy Algorithm in Data Structures Intermediate 114 min](https://www.scholarhat.com/tutorial/datastructures/greedy-algorithm "Get More Details")
## [Array]()
[Differences Between Array and Linked List Beginners 10 min](https://www.scholarhat.com/tutorial/datastructures/differences-between-arrays-and-linked-lists "Get More Details")
[Multi dimensional array in Data Structures Beginners 16 min](https://www.scholarhat.com/tutorial/datastructures/multi-dimensional-array "Get More Details")
[One dimensional Array in Data Structures with Example Beginners 15 min](https://www.scholarhat.com/tutorial/datastructures/one-dimensional-array "Get More Details")
[Suffix Array and Suffix Tree in Data Structures & Applications Advanced 18 min](https://www.scholarhat.com/tutorial/datastructures/suffix-array-and-suffix-tree-in-data-structures "Get More Details")
## [Arrays]()
[Two dimensional Array In Data Structure Beginners 18 min](https://www.scholarhat.com/tutorial/datastructures/two-dimensional-array "Get More Details")
[Types of Arrays in Data Structures: 2D, 3D, Jagged Arrays Beginners 22 min](https://www.scholarhat.com/tutorial/datastructures/types-of-arrays-in-data-structures "Get More Details")
[Arrays in Data Structures - Types, Representation & Algorithm (With Examples) Beginners 47 min](https://www.scholarhat.com/tutorial/datastructures/arrays-in-data-structures "Get More Details")
## [B-Tree]()
[B Tree: An Efficient Data Structure Beginners 12 min](https://www.scholarhat.com/tutorial/datastructures/b-tree-in-data-structure "Get More Details")
## [Data Structures Basics]()
[What are Data Structures - Types of Data Structures (Complete Guide) Beginners 26 min](https://www.scholarhat.com/tutorial/datastructures/what-are-data-structures-types-of-data-structures "Get More Details")
## [Recursion]()
[Recursion in Data Structures: Recursive Function Beginners 11 min](https://www.scholarhat.com/tutorial/datastructures/recursion-in-data-structures "Get More Details")
## [Searching Algorithms]()
[Complexity Analysis of Data Structures and Algorithms Beginners 16 min](https://www.scholarhat.com/tutorial/datastructures/complexity-analysis-of-data-structures-and-algorithms "Get More Details")
[Searching in Data Structures - Its Types, Methods & Techniques Beginners 18 min](https://www.scholarhat.com/tutorial/datastructures/searching-in-data-structures "Get More Details")
[Brute Force Algorithm in Data Structures: Types, Advantages, Disadvantages Beginners 8 min](https://www.scholarhat.com/tutorial/datastructures/brute-force-algorithm-in-data-structures "Get More Details")
## [Big O Notation]()
[Big O Notation in Data Structures: Time and Space Complexity Beginners 7 min](https://www.scholarhat.com/tutorial/datastructures/big-o-notation-explained-time-and-space-complexity "Get More Details")
## [Stack]()
[Stack in Data Structures: Implementations in Java, Python, & C++ Beginners 87 min](https://www.scholarhat.com/tutorial/datastructures/stack-data-structure-operations-implementation "Get More Details")
## [Linear Search]()
[What is Linear Search in Data Structures - Its Algorithm, Working, & Complexity Intermediate 15 min](https://www.scholarhat.com/tutorial/datastructures/linear-search-in-data-structures "Get More Details")
## [Divide and Conquer Algorithm]()
[Divide and Conquer Algorithm in Data Structures - Its Working, Advantages & Disadvantages Intermediate 8 min](https://www.scholarhat.com/tutorial/datastructures/divide-and-conqure-algorithm "Get More Details")
## [Heap]()
[Heap in Data Structures Advanced 23 min](https://www.scholarhat.com/tutorial/datastructures/heap-in-data-structures "Get More Details")
## [Hashing]()
[Hashing in Data Structures: Types and Functions \[With Examples\] Advanced 21 min](https://www.scholarhat.com/tutorial/datastructures/hashing-in-data-structures "Get More Details")
[Hash Table in Data Structures Advanced 25 min](https://www.scholarhat.com/tutorial/datastructures/hash-table-in-data-structures "Get More Details")
## [Graph]()
[What is a Graph in Data Structures and its Types? Advanced 20 min](https://www.scholarhat.com/tutorial/datastructures/graph-in-data-structures "Get More Details")
## [BFS]()
[Breadth First Traversal and Depth First Traversal in Data Structure Advanced 33 min](https://www.scholarhat.com/tutorial/datastructures/breadth-first-traversal-and-depth-first-traversal "Get More Details")
## [Interview]()
[Top 45+ DSA MCQ Questions with Answers {Updated} Questions 25 min](https://www.scholarhat.com/tutorial/datastructures/data-structures-mcqs "Get More Details")
[DSA Interview Questions and Answers (Freshers to Experienced) Questions 41 min](https://www.scholarhat.com/tutorial/datastructures/data-structure-interview-questions-and-answers "Get More Details")
## [Roadmaps]()
[DSA Roadmap for Beginners: Step-by-Step Guide to Master in DSA Career 28 min](https://www.scholarhat.com/tutorial/datastructures/roadmap-to-learn-dsa "Get More Details")
## [Quick Guide]()
[Data Structure Cheat Sheet: Complete Guide Career 37 min](https://www.scholarhat.com/tutorial/datastructures/data-structures-cheat-sheet "Get More Details")
1. [Home](https://www.scholarhat.com/)
2. [Tutorials](https://www.scholarhat.com/tutorial)
3. [Datastructures](https://www.scholarhat.com/tutorial/datastructures)
4. Bellman Ford’S Algorithm ..

# Bellman Ford’s Algorithm in Data Structures - Working, Example and Applications
23 Sep 2025
Advanced
13\.4K Views
32 min read

Learn with an interactive course and practical hands-on labs
### Free DSA Online Course with Certification
[ Start Learning Free](https://www.scholarhat.com/free-course/data-structures-algorithms-course?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Free_Course&utm_content=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm) [DSA Problems](https://www.scholarhat.com/problems?utm_source=Scholarhat&utm_medium=Article&utm_campaign=DSA_Problems&utm_content=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm) [ Free Interview books](https://www.scholarhat.com/books/data-structures-and-algorithms-interview-questions-and-answers-book-pdf) [ Skill Test](https://www.scholarhat.com/skill-test/datastructures)
The Bellman-Ford Algorithm is an algorithm that computes shortest paths in a directed graph. This algorithm can help you understand the implications of multiple connections and how they determine efficient travel routes or optimal cost networks.
In this [**DSA tutorial**](https://www.scholarhat.com/tutorial/datastructures), we will explore the Bellman-Ford Algorithm to get a better understanding of its basic principles and practical applications. What is the difference between Dijkstra and Bellman-Ford algorithm?. **By 2027, 80% of coding interviews will focus on DSA skills. Ace them with our [Free Data Structures and Algorithms Course](https://www.scholarhat.com/free-course/data-structures-algorithms-course) today\!**
## What is Bellman Ford's Algorithm in Data Structures?
Bellman-Ford algorithm is used to calculate the **shortest paths** from a single source vertex to all vertices in the graph. This algorithm even works on graphs with a negative edge weight cycle i.e. a cycle of edges with the sum of weights equal to a negative number. This algorithm follows the bottom-up approach.
At its core, the algorithm works by building up a set of "distance estimates" for each node in a graph, gradually refining them until every node has the best possible estimate. While the algorithm may seem complex at first glance, its ability to solve a wide variety of problems has made it a crucial tool for many fields, from computer science to civil engineering.
## Bellman Ford's Algorithm Example
Here's an example of the bellman ford's algorithm in action:
Let's consider a directed weighted graph with the following edges and their respective weights:
- Edge 1: A -\> B, weight = 2
- Edge 2: A -\> C, weight = 4
- Edge 3: B -\> C, weight = 1
- Edge 4: B -\> D, weight = 7
- Edge 5: C -\> D, weight = 3
- Edge 6: D -\> A, weight = 5
We want to find the shortest paths from a source vertex (let's say A) to all other vertices in the graph.
**Step 1: Initialization**
We set the distance to the source vertex as 0, and all other distances as infinity.
- Distance to A: 0
- Distance to B: Infinity
- Distance to C: Infinity
- Distance to D: Infinity
**Step 2: Relaxation**
We iterate over all the edges \|V\| - 1 time, where \|V\| is the number of vertices in the graph, and relax the edges. In each iteration, we update the distances if we find a shorter path.
**Iteration 1:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 4
- Distance to D: Infinity
**Iteration 2:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
**Iteration 3:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
**Iteration 4:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
**Iteration 5:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
**Step 3: Negative cycle detection**
After \|V\| - 1 iterations, we check for any negative cycles in the graph. In this example, there are no negative cycles.
**Step 4: Result**
The final distances from the source vertex A to all other vertices are as follows:
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
So, the shortest path from A to B is 2, from A to C is 3, and from A to D is 6.
##
**Read More - [Data Structure Interview Questions and Answers](https://www.scholarhat.com/tutorial/datastructures/data-structure-interview-questions-and-answers)**
## How Bellman Ford's Algorithm Works?
Bellman-Ford's algorithm is a shortest path algorithm used to find the shortest paths from a source vertex to all other vertices in a weighted directed graph. It can handle graphs with negative edge weights, unlike Dijkstra's algorithm, which requires non-negative weights. The algorithm works as follows:
1. Initialize the distance values for all vertices in the graph as infinity, except for the source vertex, which is set to 0. Also, initialize the predecessor of all vertices as undefined.
Relaxation step: Repeat the following process \|V\|-1 times, where \|V\| is the number of vertices in the graph.

2. For each edge (u, v) in the graph, where u is the source vertex and v is the destination vertex:
- If the distance from the source vertex to u plus the weight of the edge (u, v) is less than the current distance value of v, update the distance of v with this new value.
- Also, update the predecessor of v as u.

3. **Check for negative-weight cycles:** Repeat the following process for each edge (u, v) in the graph.
- If the distance from the source vertex to u plus the weight of the edge (u, v) is less than the current distance value of v, then there is a negative-weight cycle in the graph.

4. After completing the relaxation step \|V\|-1 times, the algorithm will have calculated the shortest distances from the source vertex to all other vertices in the graph (if no negative-weight cycles exist). If there is a negative-weight cycle, step 3 will detect it.

5. If required, the shortest paths can be reconstructed using the predecessor information. Starting from the destination vertex, follow the predecessor pointers until reaching the source vertex to obtain the shortest path.

The algorithm guarantees the correct shortest path distances if there are no negative-weight cycles reachable from the source vertex. However, if there is a negative-weight cycle that can be reached from the source vertex, the algorithm will detect it in step 3. In such cases, the algorithm cannot provide meaningful shortest path distances, as the negative-weight cycle allows for infinite negative weight reductions

## Bellman Ford's Algorithm Pseudocode
Bellman Ford's algorithm, is used to find the shortest paths from a single source vertex to all other vertices in a weighted directed graph. The algorithm can handle negative edge weights but detects negative cycles.
```
```
In this pseudocode:
- **The graph**represents the input graph.
- **The source** is the source vertex from which to find the shortest paths.
- **distance\[v\]** represents the shortest distance from the source to vertex v.
- **predecessor\[v\]** stores the predecessor of vertex v in the shortest path.
The algorithm consists of four main steps:
1. **Initialization:** Set the distance of all vertices to infinity, except for the source vertex, which is set to 0. Set the predecessor of all vertices to null.
2. **Relaxation:** Perform a relaxation step for each edge in the graph \|V\|-1 times. The relaxation step updates the distance to each vertex v if there exists a shorter path through vertex u.
3. **Check for negative cycles:** Perform one more iteration to check for negative cycles. If a shorter path can still be found, then there exists a negative cycle in the graph.
4. **Output the shortest paths:** After completing the algorithm, the shortest distances and predecessors are returned.
Note that \|V\| represents the number of vertices in the graph, and weight(u, v) returns the weight/cost of the edge (u, v).
## Implementation of Bellman Ford’s Algorithm
- [Python](https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm#pythonTab1)
- [Java](https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm#javaTab1)
- [C++](https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm#cppTab1)
```
class Graph:
def __init__(self, vertices):
self.V = vertices # No. of vertices
self.graph = []
# function to add an edge to graph
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
# utility function used to print the solution
def printArr(self, dist):
print("Vertex Distance from Source")
for i in range(self.V):
print("{0}\t\t{1}".format(i, dist[i]))
# The main function that finds shortest distances from src to
# all other vertices using Bellman-Ford algorithm. The function
# also detects negative weight cycle
def BellmanFord(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 _ 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
self.printArr(dist)
# Driver's code
if __name__ == '__main__':
g = Graph(5)
g.addEdge(0, 1, -1)
g.addEdge(0, 2, 4)
g.addEdge(1, 2, 3)
g.addEdge(1, 3, 2)
g.addEdge(1, 4, 2)
g.addEdge(3, 2, 5)
g.addEdge(3, 1, 1)
g.addEdge(4, 3, -3)
# function call
g.BellmanFord(0)
```
Run Code \>\>
```
import java.io.*;
import java.lang.*;
import java.util.*;
// A class to represent a connected, directed and weighted
// graph
class Graph {
// A class to represent a weighted edge in graph
class Edge {
int src, dest, weight;
Edge() { src = dest = weight = 0; }
};
int V, E;
Edge edge[];
// Creates a graph with V vertices and E edges
Graph(int v, int e)
{
V = v;
E = e;
edge = new Edge[e];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();
}
// The main function that finds shortest distances from
// src to all other vertices using Bellman-Ford
// algorithm. The function also detects negative weight
// cycle
void BellmanFord(Graph graph, int src)
{
int V = graph.V, E = graph.E;
int dist[] = new int[V];
// Step 1: Initialize distances from src to all
// other vertices as INFINITE
for (int i = 0; i < V; ++i)
dist[i] = Integer.MAX_VALUE;
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 (int i = 1; i < V; ++i) {
for (int j = 0; j < E; ++j) {
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// 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 (int j = 0; j < E; ++j) {
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE
&& dist[u] + weight < dist[v]) {
System.out.println(
"Graph contains negative weight cycle");
return;
}
}
printArr(dist, V);
}
// A utility function used to print the solution
void printArr(int dist[], int V)
{
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; ++i)
System.out.println(i + "\t\t" + dist[i]);
}
// Driver's code
public static void main(String[] args)
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
Graph graph = new Graph(V, E);
// add edge 0-1 (or A-B in above figure)
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = -1;
// add edge 0-2 (or A-C in above figure)
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 4;
// add edge 1-2 (or B-C in above figure)
graph.edge[2].src = 1;
graph.edge[2].dest = 2;
graph.edge[2].weight = 3;
// add edge 1-3 (or B-D in above figure)
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 2;
// add edge 1-4 (or B-E in above figure)
graph.edge[4].src = 1;
graph.edge[4].dest = 4;
graph.edge[4].weight = 2;
// add edge 3-2 (or D-C in above figure)
graph.edge[5].src = 3;
graph.edge[5].dest = 2;
graph.edge[5].weight = 5;
// add edge 3-1 (or D-B in above figure)
graph.edge[6].src = 3;
graph.edge[6].dest = 1;
graph.edge[6].weight = 1;
// add edge 4-3 (or E-D in above figure)
graph.edge[7].src = 4;
graph.edge[7].dest = 3;
graph.edge[7].weight = -3;
// Function call
graph.BellmanFord(graph, 0);
}
}
```
Run Code \>\>
```
#include <iostream>
using namespace std;
// a structure to represent a weighted edge in graph
struct Edge {
int src, dest, weight;
};
// a structure to represent a connected, directed and
// weighted graph
struct Graph {
// V-> Number of vertices, E-> Number of edges
int V, E;
// graph is represented as an array of edges.
struct Edge* edge;
};
// Creates a graph with V vertices and E edges
struct Graph* createGraph(int V, int E)
{
struct Graph* graph = new Graph;
graph->V = V;
graph->E = E;
graph->edge = new Edge[E];
return graph;
}
// A utility function used to print the solution
void printArr(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < n; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}
// The main function that finds shortest distances from src
// to all other vertices using Bellman-Ford algorithm. The
// function also detects negative weight cycle
void BellmanFord(struct Graph* graph, int src)
{
int V = graph->V;
int E = graph->E;
int dist[V];
// Step 1: Initialize distances from src to all other
// vertices as INFINITE
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
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 (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = graph->edge[j].src;
int v = graph->edge[j].dest;
int weight = graph->edge[j].weight;
if (dist[u] != INT_MAX
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// 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 (int i = 0; i < E; i++) {
int u = graph->edge[i].src;
int v = graph->edge[i].dest;
int weight = graph->edge[i].weight;
if (dist[u] != INT_MAX
&& dist[u] + weight < dist[v]) {
printf("Graph contains negative weight cycle");
return; // If negative cycle is detected, simply
// return
}
}
printArr(dist, V);
return;
}
// Driver's code
int main()
{
/* Let us create the graph given in above example */
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
struct Graph* graph = createGraph(V, E);
// add edge 0-1 (or A-B in above figure)
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = -1;
// add edge 0-2 (or A-C in above figure)
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 4;
// add edge 1-2 (or B-C in above figure)
graph->edge[2].src = 1;
graph->edge[2].dest = 2;
graph->edge[2].weight = 3;
// add edge 1-3 (or B-D in above figure)
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 2;
// add edge 1-4 (or B-E in above figure)
graph->edge[4].src = 1;
graph->edge[4].dest = 4;
graph->edge[4].weight = 2;
// add edge 3-2 (or D-C in above figure)
graph->edge[5].src = 3;
graph->edge[5].dest = 2;
graph->edge[5].weight = 5;
// add edge 3-1 (or D-B in above figure)
graph->edge[6].src = 3;
graph->edge[6].dest = 1;
graph->edge[6].weight = 1;
// add edge 4-3 (or E-D in above figure)
graph->edge[7].src = 4;
graph->edge[7].dest = 3;
graph->edge[7].weight = -3;
// Function call
BellmanFord(graph, 0);
return 0;
}
```
Run Code \>\>
#### Output
```
Vertex Distance from Source
0 0
1 -1
2 2
3 -2
4 1
```
## Applications of Bellman Ford's Algorithm
1. **Routing protocols:** The Bellman-Ford algorithm is widely used in computer networks as the basis for distance-vector routing protocols. These protocols are responsible for determining the best path for data packets to travel through a network. Examples of routing protocols that use the Bellman-Ford algorithm include the Routing Information Protocol (RIP) and the Border Gateway Protocol (BGP).
2. **Network topology analysis:** The Bellman-Ford algorithm can be used to analyze and understand the topology of a network. By running the algorithm on a network graph, it can determine the shortest path and associated costs between different nodes. This information is valuable for network administrators to optimize network performance and identify potential bottlenecks.
3. **Internet Service Providers (ISPs):** ISPs use the Bellman-Ford algorithm for network traffic engineering and to ensure efficient routing of data across their networks. By applying the algorithm to the network topology, ISPs can determine the best path for data packets to reach their destination, considering factors such as link capacities, congestion, and network policies.
4. **Distance vector protocols in wireless sensor networks:** Wireless sensor networks often have limited resources, such as battery power and computing capabilities. The Bellman-Ford algorithm can be implemented in these networks to compute the shortest path while considering energy constraints and other network-specific requirements.
5. **Virtual Private Networks (VPNs):** The Bellman-Ford algorithm is used in VPNs to determine the optimal path for network traffic between different nodes in the VPN infrastructure. It helps establish secure and efficient communication between geographically distributed networks.
6. **Resource allocation in cloud computing:** The Bellman-Ford algorithm can be used to allocate resources in cloud computing environments. By modeling the cloud infrastructure as a graph, the algorithm can find the shortest path and associated costs between different resources, such as servers, storage, and network components. This information can assist in optimizing resource allocation and load balancing.
## Complexity Analysis of Bellman Ford's Algorithm
1. **Time Complexity**
| | |
|---|---|
| **Case** | **Time Complexity** |
| **Best Case** | O(E) |
| **Average Case** | O(VE) |
| **Worst Case** | O(VE) |
2. **Space Complexity:** The [**space complexity**](https://www.scholarhat.com/tutorial/datastructures/complexity-analysis-of-data-structures-and-algorithms) of Bellman Ford's Algorithm is O(V).
##### Summary
The Bellman-Ford Algorithm is a fundamental algorithm used to find the shortest paths in a graph, considering the weights or costs associated with each edge. It is commonly used in computer networks and routing protocols. Overall, the Bellman-Ford Algorithm is a versatile and widely used algorithm for solving shortest-path problems in various domains, enabling efficient routing and resource allocation in networks.
**Average Java Solution Architect earns ₹35–45 LPA. Don’t let your career stall at ₹8–10 LPA—Enroll now in our [Java Architect Course](https://www.scholarhat.com/job-oriented/java-solution-architect-certification-training) to fast-track your growth.**
### FAQs
### Q1. What is the worst case time complexity of Bellman Ford's Algorithm?
The worst-case time complexity of Bellman Ford's Algorithm is O(VE).
### Q2. Name some routing protocols that use the Bellman-Ford's Algorithm.
Routing Information Protocol (RIP) and the Border Gateway Protocol (BGP) are some routing protocols that use the Bellman-Ford's Algorithm
### Q3. How many steps are there in Bellman Ford's Algorithm?
The Bellman Ford's algorithm consists of four main steps.
## Take our Datastructures skill challenge to evaluate yourself\!
![]()
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.
[GET FREE CHALLENGE](https://www.scholarhat.com/skill-test/datastructures?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Get_Free_Challange&utm_term=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm)
**Share Article**
Similar Articles
- [**0/1 Knapsack Problem**](https://www.scholarhat.com/tutorial/datastructures/knapsack-problem)
- [**AVL Tree in Data Structures with Examples**](https://www.scholarhat.com/tutorial/datastructures/avl-tree-in-data-structures)
- [**Bubble Sort Algorithm**](https://www.scholarhat.com/tutorial/datastructures/bubble-sort-algorithm)
- [**Data Structure Cheat Sheet: Complete Guide**](https://www.scholarhat.com/tutorial/datastructures/data-structures-cheat-sheet)
- [**What is a Priority Queue Data Structure? Implementation, Type & Many More**](https://www.scholarhat.com/tutorial/datastructures/priority-queue-in-data-structures)
- [**Radix Sort in Data Structures - Its Algorithm, Working, & Complexity**](https://www.scholarhat.com/tutorial/datastructures/radix-sort-in-data-structures)
[** Previous Tutorial**Tower of Hanoi in Data Structures](https://www.scholarhat.com/tutorial/datastructures/tower-of-hanoi-in-data-structures)
[**Next Tutorial **Top 45+ DSA MCQ Questions with Answers {Updated}](https://www.scholarhat.com/tutorial/datastructures/data-structures-mcqs)
###### About Author
 [View Profile](https://www.scholarhat.com/mentors/amit-ghosh)
Amit Kumar Ghosh (SDE and Mentor)
***
As a software developer with a wealth of experience, he brings a unique combination of technical acumen and a passion for mentorship to my role. With 6 years of experience, he has honed the skills in C/C++, Java, Python, SQL, C\#, JavaScript, React, Java Spring etc. and has a proven track record of delivering high-quality, scalable software solutions and core Computer fundamental knowledge DSA, OOPs, CN, OS etc.
As a teacher, his approach revolves around interactive techniques, prioritizing hands-on learning and real-world projects. He explains concepts clearly, offer practical examples, and encourage questions to foster a supportive environment.
Our Courses
[![Data Structures & Algorithms Course For Beginners]() Data Structures & Algorithms Course For Beginners Free Free DSA Online Course with Certification, Dsa Course Free, Free Dsa Course With Certificate, Free Dsa Course View More](https://www.scholarhat.com/free-course/data-structures-algorithms-course?utm_source=training_programs&utm_medium=text&utm_campaign=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm "Data Structures & Algorithms Course For Beginners")
[![C++ Programming Course For Beginners]() C++ Programming Course For Beginners Free Free C++ Online Course with Certification in 2025! Designed for beginners, learn and certify in 21 days. Don’t miss out—register now and start coding! View More](https://www.scholarhat.com/free-course/cpp-course-for-beginners?utm_source=training_programs&utm_medium=text&utm_campaign=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm "C++ Programming Course For Beginners")
[![Java Programming Course For Beginners]() Java Programming Course For Beginners Free Join our free Java course online in 2025! Gain expertise, build projects, and earn a certification. Start your programming career—register now for free! View More](https://www.scholarhat.com/free-course/java-course?utm_source=training_programs&utm_medium=text&utm_campaign=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm "Java Programming Course For Beginners")
[![Python Programming Course For Beginners]() Python Programming Course For Beginners Free Welcome to the Python Programming for Beginners course! This comprehensive and free course is your gateway to the exciting world of Python programming. Whether you're an absolute beginner with no prior coding experience. View More](https://www.scholarhat.com/free-course/python-course-for-beginners?utm_source=training_programs&utm_medium=text&utm_campaign=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm "Python Programming Course For Beginners")
##### Live Training - Book Free Demo

###### Azure Solution Architect Certification Training
18 Apr
•
05:30PM - 07:30PM IST
Get Job-Ready
•
Certification
[TRY FREE DEMO](https://www.scholarhat.com/training/microsoft-azure-solution-architect-certification?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Live_Class_Schedule&utm_term=/tutorial/datastructures/bellman-fords-algorithm)

###### .NET Software Architecture and Design Training
18 Apr
•
08:30PM - 10:30PM IST
Get Job-Ready
•
Certification
[TRY FREE DEMO](https://www.scholarhat.com/training/software-architecture-design-training?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Live_Class_Schedule&utm_term=/tutorial/datastructures/bellman-fords-algorithm)

###### ASP.NET Core Certification Training
18 Apr
•
07:00AM - 09:00AM IST
Get Job-Ready
•
Certification
[TRY FREE DEMO](https://www.scholarhat.com/training/aspnet-core-certification-training?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Live_Class_Schedule&utm_term=/tutorial/datastructures/bellman-fords-algorithm)

###### AI-Driven .NET Tech Lead Program
18 Apr
•
07:00AM - 09:00AM IST
Get Job-Ready
•
Certification
[TRY FREE DEMO](https://www.scholarhat.com/job-oriented/net-tech-lead-certification-training?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Live_Class_Schedule&utm_term=/tutorial/datastructures/bellman-fords-algorithm)

###### React Certification Training
18 Apr
•
07:00AM - 09:00AM IST
Get Job-Ready
•
Certification
[TRY FREE DEMO](https://www.scholarhat.com/training/reactjs-certification-training?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Live_Class_Schedule&utm_term=/tutorial/datastructures/bellman-fords-algorithm)
Free Master Classes
17
Apr
Become a Multi-Cloud AI Engineer: Build, Train & Deploy AI Systems
[Register Now](https://www.scholarhat.com/master-classes/build-train-deploy-ai-systems-multi-cloud?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Upcoming_Master_Class&utm_content=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm)
25
Apr
Build & Deploy Your First AI App with Python, Azure & AWS
[Register Now](https://www.scholarhat.com/master-classes/build-and-deploy-ai-systems-multi-cloud?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Upcoming_Master_Class&utm_content=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm)
26
Apr
Java Microservices in Production: Spring Boot to AWS Deployment
[Register Now](https://www.scholarhat.com/master-classes/java-solution-architect?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Upcoming_Master_Class&utm_content=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm)
26
Apr
From Monolith to Microservices: Scalable Architecture with .NET, Azure & Kubernetes
[Register Now](https://www.scholarhat.com/master-classes/monolith-to-micro-services-architecture?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Upcoming_Master_Class&utm_content=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm)
 LEAD-ACE: EdTech Platform
100% Live Sessions
 600+ Quick notes
 900+ Hands-on labs
 50+ Real-world projects
 45+ Interview books
#### Job Ready Tracks
[.NET & Azure Solution Architect Program](https://www.scholarhat.com/job-oriented/net-azure-solution-architect-certification-training) \| [AI-Driven .NET Tech Lead Program](https://www.scholarhat.com/job-oriented/net-tech-lead-certification-training) \| [AI-Driven Java Tech Lead Program](https://www.scholarhat.com/job-oriented/java-tech-lead-certification-training) \| [AI-Powered Full-Stack .NET Developer Program](https://www.scholarhat.com/job-oriented/full-stack-net-developer-certification-training) \| [Azure AI Architect Program](https://www.scholarhat.com/job-oriented/azure-ai-architect-certification-training) \| [Multi-Cloud AI & GenAI Engineer (Azure & AWS)](https://www.scholarhat.com/job-oriented/multi-cloud-ai-genai-engineer-certification-training) \| [Multi-Cloud AI Architect (Azure & AWS)](https://www.scholarhat.com/job-oriented/multi-cloud-ai-architect-certification-training)
#### Popular Live Training
[.NET AI & ML Engineer Certification Training](https://www.scholarhat.com/training/net-ai-ml-certification-training) \| [.NET Certification Training](https://www.scholarhat.com/training/net-certification-training) \| [.NET Microservices Certification Training](https://www.scholarhat.com/training/net-microservices-certification-training) \| [.NET Software Architecture and Design Training](https://www.scholarhat.com/training/software-architecture-design-training) \| [Angular Certification Training](https://www.scholarhat.com/training/angular-certification-training) \| [ASP.NET Core Certification Training](https://www.scholarhat.com/training/aspnet-core-certification-training) \| [AWS AI & Gen AI Engineer Certification Training](https://www.scholarhat.com/training/aws-ai-engineer-certification-training) \| [AWS Developer Certification Training](https://www.scholarhat.com/training/aws-developer-associate-certification-training) \| [AWS Solutions Architect Certification Training](https://www.scholarhat.com/training/aws-solution-architect-certification-training) \| [Azure Agentic AI Engineer Certification Training](https://www.scholarhat.com/training/azure-agentic-ai-engineer-certification-training) \| [Azure AI & Gen AI Engineer Certification Training](https://www.scholarhat.com/training/azure-ai-engineer-certification-training) \| [Azure Developer Certification Training](https://www.scholarhat.com/training/microsoft-azure-developer-associate-certification-training) \| [Azure DevOps Certification Training](https://www.scholarhat.com/training/azure-devops-certification-training) \| [Azure Solution Architect Certification Training](https://www.scholarhat.com/training/microsoft-azure-solution-architect-certification) \| [Blazor Certification Training](https://www.scholarhat.com/training/blazor-certification-training) \| [Career Launchpad Program](https://www.scholarhat.com/training/career-interview-coaching-course) \| [Confidence, Communication & Leadership for Software Engineers](https://www.scholarhat.com/training/confidence-communication-leadership-software-engineers) \| [Data Structures and Algorithms Training](https://www.scholarhat.com/training/data-structures-algorithms-certification-training) \| [Java Microservices Certification Training](https://www.scholarhat.com/training/java-microservices-certification-training) \| [Python For Data Science and AI/ML Certification Training](https://www.scholarhat.com/training/python-data-science-ai-certification-training) \| [React Certification Training](https://www.scholarhat.com/training/reactjs-certification-training) \| [The Top 1% Tech Leader Program](https://www.scholarhat.com/training/tech-leadership-training-program)
#### Platform
- [Live Training](https://www.scholarhat.com/training)
- [Free Courses](https://www.scholarhat.com/free-course)
- [Hands-on Labs](https://www.scholarhat.com/labs)
- [Real-World Projects](https://www.scholarhat.com/projects)
- [DSA Problems](https://www.scholarhat.com/problems)
- [Quick Notes](https://www.scholarhat.com/quicknotes)
- [Free Interview Books](https://www.scholarhat.com/books)
- [Corporate Training](https://www.scholarhat.com/corporate-training)
#### Company
- [About Us](https://www.scholarhat.com/about-us)
- [Contact Us](https://www.scholarhat.com/contact-us)
- [Terms & Conditions](https://www.scholarhat.com/terms-and-conditions)
- [Privacy Policy](https://www.scholarhat.com/privacy-policy)
- [Refund Policy](https://www.scholarhat.com/refund-policy)
- [Subscription Policy](https://www.scholarhat.com/subscription-policy)
- [Verify Certificate](https://www.scholarhat.com/certificate/verify)
- [Become An Instructor](https://www.scholarhat.com/become-an-instructor)
#### Resources
- [Live Training Membership](https://www.scholarhat.com/membership/live)
- [Master Classes](https://www.scholarhat.com/master-classes)
- [Coding Playground](https://www.scholarhat.com/compiler)
- [Skill Tests](https://www.scholarhat.com/skill-tests)
- [Job Openings](https://www.scholarhat.com/jobs)
- [Mentors](https://www.scholarhat.com/mentors)
- [Live Batches](https://www.scholarhat.com/training/batches)
- [Reviews](https://www.scholarhat.com/reviews)
#### Have any Questions?
###### Course Enquires:
- [\+91- 999 9123 502](tel:+919999123502)
- [hello@scholarhat.com](mailto:hello@scholarhat.com)
###### Tech Support:
- [\+91- 966 7279 501](tel:+919667279501)
- [support@scholarhat.com](mailto:support@scholarhat.com)
Follow Us
© 2026 Dot Net Tricks Innovation Pvt. Ltd. \| All rights reserved \| The course names and logos are the trademarks of their respective owners \| Engineered with in India.
We use cookies to make interactions with our websites and services easy and meaningful. Please read our [Privacy Policy](https://www.scholarhat.com/privacy-policy) for more details.
[Accept Cookies]() |
| Readable Markdown | The Bellman-Ford Algorithm is an algorithm that computes shortest paths in a directed graph. This algorithm can help you understand the implications of multiple connections and how they determine efficient travel routes or optimal cost networks.
In this [**DSA tutorial**](https://www.scholarhat.com/tutorial/datastructures), we will explore the Bellman-Ford Algorithm to get a better understanding of its basic principles and practical applications. What is the difference between Dijkstra and Bellman-Ford algorithm?. **By 2027, 80% of coding interviews will focus on DSA skills. Ace them with our [Free Data Structures and Algorithms Course](https://www.scholarhat.com/free-course/data-structures-algorithms-course) today\!**
## What is Bellman Ford's Algorithm in Data Structures?
Bellman-Ford algorithm is used to calculate the **shortest paths** from a single source vertex to all vertices in the graph. This algorithm even works on graphs with a negative edge weight cycle i.e. a cycle of edges with the sum of weights equal to a negative number. This algorithm follows the bottom-up approach.
At its core, the algorithm works by building up a set of "distance estimates" for each node in a graph, gradually refining them until every node has the best possible estimate. While the algorithm may seem complex at first glance, its ability to solve a wide variety of problems has made it a crucial tool for many fields, from computer science to civil engineering.
## Bellman Ford's Algorithm Example
Here's an example of the bellman ford's algorithm in action:
Let's consider a directed weighted graph with the following edges and their respective weights:
- Edge 1: A -\> B, weight = 2
- Edge 2: A -\> C, weight = 4
- Edge 3: B -\> C, weight = 1
- Edge 4: B -\> D, weight = 7
- Edge 5: C -\> D, weight = 3
- Edge 6: D -\> A, weight = 5
We want to find the shortest paths from a source vertex (let's say A) to all other vertices in the graph.
**Step 1: Initialization**
We set the distance to the source vertex as 0, and all other distances as infinity.
- Distance to A: 0
- Distance to B: Infinity
- Distance to C: Infinity
- Distance to D: Infinity
**Step 2: Relaxation**
We iterate over all the edges \|V\| - 1 time, where \|V\| is the number of vertices in the graph, and relax the edges. In each iteration, we update the distances if we find a shorter path.
**Iteration 1:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 4
- Distance to D: Infinity
**Iteration 2:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
**Iteration 3:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
**Iteration 4:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
**Iteration 5:**
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
**Step 3: Negative cycle detection**
After \|V\| - 1 iterations, we check for any negative cycles in the graph. In this example, there are no negative cycles.
**Step 4: Result**
The final distances from the source vertex A to all other vertices are as follows:
- Distance to A: 0
- Distance to B: 2
- Distance to C: 3
- Distance to D: 6
So, the shortest path from A to B is 2, from A to C is 3, and from A to D is 6.
**Read More - [Data Structure Interview Questions and Answers](https://www.scholarhat.com/tutorial/datastructures/data-structure-interview-questions-and-answers)**
## How Bellman Ford's Algorithm Works?
Bellman-Ford's algorithm is a shortest path algorithm used to find the shortest paths from a source vertex to all other vertices in a weighted directed graph. It can handle graphs with negative edge weights, unlike Dijkstra's algorithm, which requires non-negative weights. The algorithm works as follows:
1. Initialize the distance values for all vertices in the graph as infinity, except for the source vertex, which is set to 0. Also, initialize the predecessor of all vertices as undefined.
Relaxation step: Repeat the following process \|V\|-1 times, where \|V\| is the number of vertices in the graph.

2. For each edge (u, v) in the graph, where u is the source vertex and v is the destination vertex:
- If the distance from the source vertex to u plus the weight of the edge (u, v) is less than the current distance value of v, update the distance of v with this new value.
- Also, update the predecessor of v as u.

3. **Check for negative-weight cycles:** Repeat the following process for each edge (u, v) in the graph.
- If the distance from the source vertex to u plus the weight of the edge (u, v) is less than the current distance value of v, then there is a negative-weight cycle in the graph.

4. After completing the relaxation step \|V\|-1 times, the algorithm will have calculated the shortest distances from the source vertex to all other vertices in the graph (if no negative-weight cycles exist). If there is a negative-weight cycle, step 3 will detect it.

5. If required, the shortest paths can be reconstructed using the predecessor information. Starting from the destination vertex, follow the predecessor pointers until reaching the source vertex to obtain the shortest path.

The algorithm guarantees the correct shortest path distances if there are no negative-weight cycles reachable from the source vertex. However, if there is a negative-weight cycle that can be reached from the source vertex, the algorithm will detect it in step 3. In such cases, the algorithm cannot provide meaningful shortest path distances, as the negative-weight cycle allows for infinite negative weight reductions

## Bellman Ford's Algorithm Pseudocode
Bellman Ford's algorithm, is used to find the shortest paths from a single source vertex to all other vertices in a weighted directed graph. The algorithm can handle negative edge weights but detects negative cycles.
```
```
In this pseudocode:
- **The graph**represents the input graph.
- **The source** is the source vertex from which to find the shortest paths.
- **distance\[v\]** represents the shortest distance from the source to vertex v.
- **predecessor\[v\]** stores the predecessor of vertex v in the shortest path.
The algorithm consists of four main steps:
1. **Initialization:** Set the distance of all vertices to infinity, except for the source vertex, which is set to 0. Set the predecessor of all vertices to null.
2. **Relaxation:** Perform a relaxation step for each edge in the graph \|V\|-1 times. The relaxation step updates the distance to each vertex v if there exists a shorter path through vertex u.
3. **Check for negative cycles:** Perform one more iteration to check for negative cycles. If a shorter path can still be found, then there exists a negative cycle in the graph.
4. **Output the shortest paths:** After completing the algorithm, the shortest distances and predecessors are returned.
Note that \|V\| represents the number of vertices in the graph, and weight(u, v) returns the weight/cost of the edge (u, v).
## Implementation of Bellman Ford’s Algorithm
- [Python](https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm#pythonTab1)
- [Java](https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm#javaTab1)
- [C++](https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm#cppTab1)
```
class Graph:
def __init__(self, vertices):
self.V = vertices # No. of vertices
self.graph = []
# function to add an edge to graph
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
# utility function used to print the solution
def printArr(self, dist):
print("Vertex Distance from Source")
for i in range(self.V):
print("{0}\t\t{1}".format(i, dist[i]))
# The main function that finds shortest distances from src to
# all other vertices using Bellman-Ford algorithm. The function
# also detects negative weight cycle
def BellmanFord(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 _ 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
self.printArr(dist)
# Driver's code
if __name__ == '__main__':
g = Graph(5)
g.addEdge(0, 1, -1)
g.addEdge(0, 2, 4)
g.addEdge(1, 2, 3)
g.addEdge(1, 3, 2)
g.addEdge(1, 4, 2)
g.addEdge(3, 2, 5)
g.addEdge(3, 1, 1)
g.addEdge(4, 3, -3)
# function call
g.BellmanFord(0)
```
```
import java.io.*;
import java.lang.*;
import java.util.*;
// A class to represent a connected, directed and weighted
// graph
class Graph {
// A class to represent a weighted edge in graph
class Edge {
int src, dest, weight;
Edge() { src = dest = weight = 0; }
};
int V, E;
Edge edge[];
// Creates a graph with V vertices and E edges
Graph(int v, int e)
{
V = v;
E = e;
edge = new Edge[e];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();
}
// The main function that finds shortest distances from
// src to all other vertices using Bellman-Ford
// algorithm. The function also detects negative weight
// cycle
void BellmanFord(Graph graph, int src)
{
int V = graph.V, E = graph.E;
int dist[] = new int[V];
// Step 1: Initialize distances from src to all
// other vertices as INFINITE
for (int i = 0; i < V; ++i)
dist[i] = Integer.MAX_VALUE;
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 (int i = 1; i < V; ++i) {
for (int j = 0; j < E; ++j) {
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// 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 (int j = 0; j < E; ++j) {
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE
&& dist[u] + weight < dist[v]) {
System.out.println(
"Graph contains negative weight cycle");
return;
}
}
printArr(dist, V);
}
// A utility function used to print the solution
void printArr(int dist[], int V)
{
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; ++i)
System.out.println(i + "\t\t" + dist[i]);
}
// Driver's code
public static void main(String[] args)
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
Graph graph = new Graph(V, E);
// add edge 0-1 (or A-B in above figure)
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = -1;
// add edge 0-2 (or A-C in above figure)
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 4;
// add edge 1-2 (or B-C in above figure)
graph.edge[2].src = 1;
graph.edge[2].dest = 2;
graph.edge[2].weight = 3;
// add edge 1-3 (or B-D in above figure)
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 2;
// add edge 1-4 (or B-E in above figure)
graph.edge[4].src = 1;
graph.edge[4].dest = 4;
graph.edge[4].weight = 2;
// add edge 3-2 (or D-C in above figure)
graph.edge[5].src = 3;
graph.edge[5].dest = 2;
graph.edge[5].weight = 5;
// add edge 3-1 (or D-B in above figure)
graph.edge[6].src = 3;
graph.edge[6].dest = 1;
graph.edge[6].weight = 1;
// add edge 4-3 (or E-D in above figure)
graph.edge[7].src = 4;
graph.edge[7].dest = 3;
graph.edge[7].weight = -3;
// Function call
graph.BellmanFord(graph, 0);
}
}
```
```
#include <iostream>
using namespace std;
// a structure to represent a weighted edge in graph
struct Edge {
int src, dest, weight;
};
// a structure to represent a connected, directed and
// weighted graph
struct Graph {
// V-> Number of vertices, E-> Number of edges
int V, E;
// graph is represented as an array of edges.
struct Edge* edge;
};
// Creates a graph with V vertices and E edges
struct Graph* createGraph(int V, int E)
{
struct Graph* graph = new Graph;
graph->V = V;
graph->E = E;
graph->edge = new Edge[E];
return graph;
}
// A utility function used to print the solution
void printArr(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < n; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}
// The main function that finds shortest distances from src
// to all other vertices using Bellman-Ford algorithm. The
// function also detects negative weight cycle
void BellmanFord(struct Graph* graph, int src)
{
int V = graph->V;
int E = graph->E;
int dist[V];
// Step 1: Initialize distances from src to all other
// vertices as INFINITE
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
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 (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = graph->edge[j].src;
int v = graph->edge[j].dest;
int weight = graph->edge[j].weight;
if (dist[u] != INT_MAX
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// 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 (int i = 0; i < E; i++) {
int u = graph->edge[i].src;
int v = graph->edge[i].dest;
int weight = graph->edge[i].weight;
if (dist[u] != INT_MAX
&& dist[u] + weight < dist[v]) {
printf("Graph contains negative weight cycle");
return; // If negative cycle is detected, simply
// return
}
}
printArr(dist, V);
return;
}
// Driver's code
int main()
{
/* Let us create the graph given in above example */
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
struct Graph* graph = createGraph(V, E);
// add edge 0-1 (or A-B in above figure)
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = -1;
// add edge 0-2 (or A-C in above figure)
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 4;
// add edge 1-2 (or B-C in above figure)
graph->edge[2].src = 1;
graph->edge[2].dest = 2;
graph->edge[2].weight = 3;
// add edge 1-3 (or B-D in above figure)
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 2;
// add edge 1-4 (or B-E in above figure)
graph->edge[4].src = 1;
graph->edge[4].dest = 4;
graph->edge[4].weight = 2;
// add edge 3-2 (or D-C in above figure)
graph->edge[5].src = 3;
graph->edge[5].dest = 2;
graph->edge[5].weight = 5;
// add edge 3-1 (or D-B in above figure)
graph->edge[6].src = 3;
graph->edge[6].dest = 1;
graph->edge[6].weight = 1;
// add edge 4-3 (or E-D in above figure)
graph->edge[7].src = 4;
graph->edge[7].dest = 3;
graph->edge[7].weight = -3;
// Function call
BellmanFord(graph, 0);
return 0;
}
```
#### Output
```
Vertex Distance from Source
0 0
1 -1
2 2
3 -2
4 1
```
## Applications of Bellman Ford's Algorithm
1. **Routing protocols:** The Bellman-Ford algorithm is widely used in computer networks as the basis for distance-vector routing protocols. These protocols are responsible for determining the best path for data packets to travel through a network. Examples of routing protocols that use the Bellman-Ford algorithm include the Routing Information Protocol (RIP) and the Border Gateway Protocol (BGP).
2. **Network topology analysis:** The Bellman-Ford algorithm can be used to analyze and understand the topology of a network. By running the algorithm on a network graph, it can determine the shortest path and associated costs between different nodes. This information is valuable for network administrators to optimize network performance and identify potential bottlenecks.
3. **Internet Service Providers (ISPs):** ISPs use the Bellman-Ford algorithm for network traffic engineering and to ensure efficient routing of data across their networks. By applying the algorithm to the network topology, ISPs can determine the best path for data packets to reach their destination, considering factors such as link capacities, congestion, and network policies.
4. **Distance vector protocols in wireless sensor networks:** Wireless sensor networks often have limited resources, such as battery power and computing capabilities. The Bellman-Ford algorithm can be implemented in these networks to compute the shortest path while considering energy constraints and other network-specific requirements.
5. **Virtual Private Networks (VPNs):** The Bellman-Ford algorithm is used in VPNs to determine the optimal path for network traffic between different nodes in the VPN infrastructure. It helps establish secure and efficient communication between geographically distributed networks.
6. **Resource allocation in cloud computing:** The Bellman-Ford algorithm can be used to allocate resources in cloud computing environments. By modeling the cloud infrastructure as a graph, the algorithm can find the shortest path and associated costs between different resources, such as servers, storage, and network components. This information can assist in optimizing resource allocation and load balancing.
## Complexity Analysis of Bellman Ford's Algorithm
1. **Time Complexity**
| | |
|---|---|
| **Case** | **Time Complexity** |
| **Best Case** | O(E) |
| **Average Case** | O(VE) |
| **Worst Case** | O(VE) |
2. **Space Complexity:** The [**space complexity**](https://www.scholarhat.com/tutorial/datastructures/complexity-analysis-of-data-structures-and-algorithms) of Bellman Ford's Algorithm is O(V).
##### Summary
The Bellman-Ford Algorithm is a fundamental algorithm used to find the shortest paths in a graph, considering the weights or costs associated with each edge. It is commonly used in computer networks and routing protocols. Overall, the Bellman-Ford Algorithm is a versatile and widely used algorithm for solving shortest-path problems in various domains, enabling efficient routing and resource allocation in networks.
**Average Java Solution Architect earns ₹35–45 LPA. Don’t let your career stall at ₹8–10 LPA—Enroll now in our [Java Architect Course](https://www.scholarhat.com/job-oriented/java-solution-architect-certification-training) to fast-track your growth.**
### FAQs
The worst-case time complexity of Bellman Ford's Algorithm is O(VE).
Routing Information Protocol (RIP) and the Border Gateway Protocol (BGP) are some routing protocols that use the Bellman-Ford's Algorithm
The Bellman Ford's algorithm consists of four main steps.
## Take our Datastructures skill challenge to evaluate yourself\!
![]()
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.
[GET FREE CHALLENGE](https://www.scholarhat.com/skill-test/datastructures?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Get_Free_Challange&utm_term=https://www.scholarhat.com/tutorial/datastructures/bellman-fords-algorithm) |
| Shard | 76 (laksa) |
| Root Hash | 5572162201820126676 |
| Unparsed URL | com,scholarhat!www,/tutorial/datastructures/bellman-fords-algorithm s443 |