ℹ️ 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.2 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.scaler.com/topics/data-structures/bellman-ford-algorithm/ |
| Last Crawled | 2026-04-05 10:03:23 (5 days ago) |
| First Indexed | 2022-03-22 13:16:16 (4 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Bellman–Ford Algorithm | Scaler Topics |
| Meta Description | Learn about bellman ford algorithm by Scaler Topics. Bellman ford is used to calculate the shortest paths from a single source vertex to all vertices in the graph. |
| Meta Canonical | null |
| Boilerpipe Text | Overview
The
Bellman-Ford algorithm
is an example of Dynamic Programming. It starts with a starting vertex and calculates the distances of other vertices which can be reached by one edge. It then continues to find a path with two edges and so on. The Bellman-Ford algorithm follows the bottom-up approach.
What is Bellman-Ford Algorithm?
The
Bellman-Ford algorithm
computes the shortest path from a source vertex to all others in a graph, accommodating both weighted and unweighted edges. While it's generally slower than Dijkstra’s method, Bellman-Ford excels in graphs with negative edge weights and detects negative cycles, a crucial feature. This capability prevents infinite loops where path costs decrease infinitely by traversing negative cycles. Utilizing dynamic programming, Bellman-Ford employs a bottom-up approach, iteratively refining distance estimates via the "Principle of Relaxation." Starting with immediate neighbors, it progressively evaluates longer paths, converging to the optimal solution. However, if negative weight cycles exist, they can distort path distances, necessitating caution during analysis. Thus, Bellman-Ford offers a robust, albeit slower, alternative for diverse graph scenarios.
Example of Bellman Ford Algorithm
Suppose that we have a graph consisting of
5
vertices having edges between them as shown in the picture below. Now, we want to find shortest distance to each vertex
v
i
0<i<6
starting from the vertex
1
.
After performing
bellman ford algorithm
on the above graph the output array would look like -
Shortest_Distance = [0, 3, 5, 2, 5]
Where each index
'Ă'
of array denotes the shortest distance of the i
th
vertex from 1
st
vertex, 1<=i<=5.
How
Bellman Ford Algorithm
Works?
The algorithm works by iteratively relaxing the edges of the graph to find the shortest path.
Here are the step-by-step workings of the Bellman-Ford algorithm:
Step 1:
Initialize distances and predecessors
The algorithm starts by initializing the distance of the source node to
0
and the distances of all other nodes in the graph to
infinity
.
Step 2:
Relax edges
The algorithm then iteratively relaxes the edges of the graph. For each edge
u→v
with weight
w
, it checks if the distance to
v
can be improved by going through
u
. If the distance can be improved, it updates the distance of v and sets its predecessor to
u
.
Above step is repeated
V-1
times for every edge.
Step 3:
Check for negative cycles
After all the edges have been relaxed, the algorithm checks for negative cycles in the graph. A negative cycle is a cycle whose total weight is negative. If there is a negative cycle in the graph, the algorithm reports it and terminates.
Step 2
(relax edges) is repeated one more time for all the edges. If there is some edge some which can be further relaxed then we say that there is an negative cycle present in the graph.
Step 4:
Shortest paths
If there are no negative cycles in the graph, the algorithm returns the shortest path from the source node to every other node in the graph.
Input:
A 2D Array/List denoting edges and their respective weights.
A src vertex.
Output:
An array where each index denotes the shortest path length between that vertex and src vertex.
Procedure:
In this step, we would declare an array of size
V
(Number of vertexes) say
dis[]
and initialize with all of its indexes with a very big Value (preferably
INT_MAX
) except
src
which will be initialized with value
0
.
We are doing this because initially we assume that it takes infinite time to reach any of the vertices from our source vertex and we are initializing
dis[src]=0
because we are already on source vertex.
In this step, the shortest distance is calculated. For it, we would do the underlying step
V-1
times.
For every edge
u→v
make
dis[v]=min(dis[u]+ wt of edge
u→v
, dis[v])
It means whenever we are on any vertex
u
we will check if we can reach any of its neighbors in less time it is currently possible to visit, we will update the
dis[v]
to
dis[u]+wt of edge u→v
.
In this step, we will check if there exists a negative edge weight cycle traversing each and every edge
u→v
and checking if there exists
dis[u] + wt of edge
u→v
< dis[v]
then our graph contains a negative edge weight cycle because traversing the edges again and again is beneficial as it is lowering the cost to traverse the graph. -->
:::
Explanation of Bellman Ford Example
Boost Your Tech Profile! Join Our
DSA Courses
for Advanced Algorithmic Mastery. Enroll Now to Stand Out in the Coding Landscape!
Difference between Dijkstra's and Bellman Ford's Algorithm
Bellman Ford Algorithm
Dijkstra Algorithm
Its implementation is inspired by the dynamic programming approach.
Its implementation is inspired by the greedy approach.
It is easier to implement in a distributive way.
It is quite complex to implement in a distributed way.
It also works when the given graph contains a negative edge weight cycle.
It fails if a graph contains a negative edge weight cycle.
It's is more time consuming than Dijkstra's. It's Time complexity is O(VE)
It's Time complexity is O(ELogV)
Pesudocode
Codes Implementation of Bellman Ford Algorithm
C/C++ Implementation of
Bellman Ford
Java Implementation of Bellman Ford
Python Implementation of Bellman Ford
Complexity Analysis of Bellman Ford
Time Complexity
-
  Since we are traversing all the edges
V-1
times, and each time we are traversing all the
E
vertices, therefore the time complexity is
O(V.E)
.
Space Complexity
-
  Since we are using an auxiliary array
dis
of size
V
, the space complexity is
O(V)
.
  Where
V
and
E
are numbers of vertices and edges respectively.
Bonus Tip of
Bellman Ford
The algorithm can be speeded up further because in most of the cases we get our final answer after performing step
2
few times only. Because
dis
array stops getting updated after some steps, So traversing edges again and again is nothing but waste of time.
To check wether any value of
dis
gets updated in any given iteration, we can keep a flag in the outer loop of Step
2
and if it not changed in the inner for loop then we can exit from the loop becuase we have already got our answer.
Though the modification will not change the asymptotic nature of the algorithm because in some graphs we will need all the
V-1
steps to be done. But it will optmize the run time of algorithm in a "average case" i.e. random graphs.
The minor modification need to be done in step 2 is given below -
Though the average case Time Complexity would be -
O(V.E)
but in the best case it can be done in only
O(E)
time. Think of the case in which we get out of the loop after the very first or second step.
Applications
Checking for negative edge weight cycle.
For finding shortest path of all vertices from single source.
Routing Algorithms.
Join our expert-led Dynamic Programming
Free Course
to master advanced problem-solving techniques and enhance your programming prowess.
Conclusion
In this blog, we have discussed one of the most important graph algorithms i.e.
Bellman-Ford algorithm
which is used to find the shortest path to all vertices from a single source vertex in
O(VE)
time complexity.
It can find shortest distance of all vertices from single source. It can also detect if there exists a negative edge weight cycle in the given graph. Therefore, it also finds its way in many routing techniques.
If you want to upskill yourself in Data Structures and algorithms then do checkout,
Scaler
where you will get live lectures, assignments, and regular tests from the people working in your dream company. |
| Markdown | [Experience]()
[](https://www.scaler.com/?utm_source=topics)
[Academy](https://www.scaler.com/academy/?utm_source=topics)
[Data Science](https://www.scaler.com/data-science-course/?utm_source=topics)
[AI/ML](https://www.scaler.com/ai-machine-learning-course/?utm_source=topics)
[DevOps](https://www.scaler.com/devops-course/?utm_source=topics)
[Neovarsity](https://www.scaler.com/neovarsity/?utm_source=topics)
[](https://www.scaler.com/topics/)
[Topics]()
[Explore]()
[New Skill Test]()
[Courses]()
[Free Masterclass](https://www.scaler.com/topics/events/)
Search for Articles, Topics
[Experience]()
[Experience Scaler]()
[Data Structures Tutorial](https://www.scaler.com/topics/data-structures/)
Bellman–Ford Algorithm
Bellman–Ford Algorithm
[Data Structures Cheatsheet]()
# Bellman–Ford Algorithm
By Paras Yadav
7 mins read
Last updated: 22 Dec 2023
663 views
Learn via video course
FREE
[View all courses](https://www.scaler.com/topics/courses/)

DSA Problem Solving for Interviews using Java
by Jitender Punia

1000
4\.9
[Start Learning](https://www.scaler.com/topics/course/dsa-interviews-java/)
[Start Learning](https://www.scaler.com/topics/course/dsa-interviews-java/)
[View all courses](https://www.scaler.com/topics/courses/)

DSA Problem Solving for Interviews using Java
by Jitender Punia
1000
4\.9
[Start Learning](https://www.scaler.com/topics/course/dsa-interviews-java/)
[Topics Covered]()
## Overview
The Bellman-Ford algorithm is an example of Dynamic Programming. It starts with a starting vertex and calculates the distances of other vertices which can be reached by one edge. It then continues to find a path with two edges and so on. The Bellman-Ford algorithm follows the bottom-up approach.
## What is Bellman-Ford Algorithm?
The **Bellman-Ford algorithm** computes the shortest path from a source vertex to all others in a graph, accommodating both weighted and unweighted edges. While it's generally slower than Dijkstra’s method, Bellman-Ford excels in graphs with negative edge weights and detects negative cycles, a crucial feature. This capability prevents infinite loops where path costs decrease infinitely by traversing negative cycles. Utilizing dynamic programming, Bellman-Ford employs a bottom-up approach, iteratively refining distance estimates via the "Principle of Relaxation." Starting with immediate neighbors, it progressively evaluates longer paths, converging to the optimal solution. However, if negative weight cycles exist, they can distort path distances, necessitating caution during analysis. Thus, Bellman-Ford offers a robust, albeit slower, alternative for diverse graph scenarios.
## Example of Bellman Ford Algorithm
Suppose that we have a graph consisting of 5 vertices having edges between them as shown in the picture below. Now, we want to find shortest distance to each vertex *vi* *0\<i\<6* starting from the vertex 1.

After performing bellman ford algorithm on the above graph the output array would look like - Shortest\_Distance = \[0, 3, 5, 2, 5\]
Where each index 'Ă' of array denotes the shortest distance of the ith vertex from 1st vertex, 1\<=i\<=5.
## How Bellman Ford Algorithm Works?
The algorithm works by iteratively relaxing the edges of the graph to find the shortest path.
Here are the step-by-step workings of the Bellman-Ford algorithm:
**Step 1:** Initialize distances and predecessors
The algorithm starts by initializing the distance of the source node to 0 and the distances of all other nodes in the graph to infinity.
```
```
**Step 2:** Relax edges
The algorithm then iteratively relaxes the edges of the graph. For each edge *u→v* with weight w, it checks if the distance to v can be improved by going through u. If the distance can be improved, it updates the distance of v and sets its predecessor to u.
```
```
Above step is repeated *V-1* times for every edge.
```
```
**Step 3:** Check for negative cycles
After all the edges have been relaxed, the algorithm checks for negative cycles in the graph. A negative cycle is a cycle whose total weight is negative. If there is a negative cycle in the graph, the algorithm reports it and terminates. **Step 2** (relax edges) is repeated one more time for all the edges. If there is some edge some which can be further relaxed then we say that there is an negative cycle present in the graph.
```
```
**Step 4:** Shortest paths
If there are no negative cycles in the graph, the algorithm returns the shortest path from the source node to every other node in the graph.
```
```
### **Input:**
- A 2D Array/List denoting edges and their respective weights.
- A src vertex.
**Output:** An array where each index denotes the shortest path length between that vertex and src vertex.
### Procedure:
1. In this step, we would declare an array of size *V*(Number of vertexes) say *dis\[\]* and initialize with all of its indexes with a very big Value (preferably INT\_MAX) except *src* which will be initialized with value 0. We are doing this because initially we assume that it takes infinite time to reach any of the vertices from our source vertex and we are initializing *dis\[src\]=0* because we are already on source vertex.
2. In this step, the shortest distance is calculated. For it, we would do the underlying step *V-1* times. For every edge *u→v* make *dis\[v\]=min(dis\[u\]+ wt of edge *u→v*, dis\[v\])* It means whenever we are on any vertex *u* we will check if we can reach any of its neighbors in less time it is currently possible to visit, we will update the *dis\[v\]* to *dis\[u\]+wt of edge u→v*.
3. In this step, we will check if there exists a negative edge weight cycle traversing each and every edge *u→v* and checking if there exists *dis\[u\] + wt of edge *u→v* \< dis\[v\]* then our graph contains a negative edge weight cycle because traversing the edges again and again is beneficial as it is lowering the cost to traverse the graph. --\> :::
## Explanation of Bellman Ford Example

***Boost Your Tech Profile! Join Our [DSA Courses](https://www.scaler.com/courses/data-structures-and-algorithms/?utm_source=scaler-topics&utm_medium=bellman-ford-algorithm&utm_campaign=topics-dsa) for Advanced Algorithmic Mastery. Enroll Now to Stand Out in the Coding Landscape\!***
## Difference between Dijkstra's and Bellman Ford's Algorithm
| Bellman Ford Algorithm | Dijkstra Algorithm |
|---|---|
| Its implementation is inspired by the dynamic programming approach. | Its implementation is inspired by the greedy approach. |
| It is easier to implement in a distributive way. | It is quite complex to implement in a distributed way. |
| It also works when the given graph contains a negative edge weight cycle. | It fails if a graph contains a negative edge weight cycle. |
| It's is more time consuming than Dijkstra's. It's Time complexity is O(VE) | It's Time complexity is O(ELogV) |
## Pesudocode
```
```
## Codes Implementation of Bellman Ford Algorithm
- ### C/C++ Implementation of Bellman Ford
```
```
- ### Java Implementation of Bellman Ford
```
```
- ### Python Implementation of Bellman Ford
```
```
## Complexity Analysis of Bellman Ford
> - #### Time Complexity -
>
> Since we are traversing all the edges *V-1* times, and each time we are traversing all the *E* vertices, therefore the time complexity is ***O(V.E)***.
> - #### Space Complexity -
>
> Since we are using an auxiliary array *dis* of size *V*, the space complexity is ***O(V)***.
> Where *V* and *E* are numbers of vertices and edges respectively.
## Bonus Tip of Bellman Ford
The algorithm can be speeded up further because in most of the cases we get our final answer after performing step 2 few times only. Because *dis* array stops getting updated after some steps, So traversing edges again and again is nothing but waste of time.
To check wether any value of *dis* gets updated in any given iteration, we can keep a flag in the outer loop of Step 2 and if it not changed in the inner for loop then we can exit from the loop becuase we have already got our answer.
Though the modification will not change the asymptotic nature of the algorithm because in some graphs we will need all the *V-1* steps to be done. But it will optmize the run time of algorithm in a "average case" i.e. random graphs.
The minor modification need to be done in step 2 is given below -
```
```
Though the average case Time Complexity would be - *O(V.E)* but in the best case it can be done in only *O(E)* time. Think of the case in which we get out of the loop after the very first or second step.
## Applications
- Checking for negative edge weight cycle.
- For finding shortest path of all vertices from single source.
- Routing Algorithms.
***Join our expert-led Dynamic Programming [Free Course](https://www.scaler.com/topics/course/dynamic-programming/) to master advanced problem-solving techniques and enhance your programming prowess.***
## Conclusion
- In this blog, we have discussed one of the most important graph algorithms i.e. Bellman-Ford algorithm which is used to find the shortest path to all vertices from a single source vertex in *O(VE)* time complexity.
- It can find shortest distance of all vertices from single source. It can also detect if there exists a negative edge weight cycle in the given graph. Therefore, it also finds its way in many routing techniques.
- If you want to upskill yourself in Data Structures and algorithms then do checkout, [Scaler](https://www.scaler.com/) where you will get live lectures, assignments, and regular tests from the people working in your dream company.

Got suggestions? [We would love to hear your feedback.]()
Your feedback is important to help us improve
[Close]()
[Submit]()
[](https://www.scaler.com/topics/)
A Free learning platform
made with  by [](https://www.scaler.com/?utm_source=topics&utm_medium=footer)
[](https://www.instagram.com/scaler_official/)
[](https://www.youtube.com/c/SCALER)
[](https://twitter.com/scaler_official)
[](https://www.facebook.com/scalerofficial)
[](https://www.linkedin.com/school/scalerofficial/mycompany/)
[](https://discord.com/invite/gD2ZTC5j8K)
Explore Scaler
- [Academy](https://www.scaler.com/academy/?utm_source=topics&utm_medium=footer)
- [Data Science & ML](https://www.scaler.com/data-science-course/?utm_source=topics&utm_medium=footer)
- [AI and Machine Learning](https://www.scaler.com/ai-machine-learning-course/?utm_source=topics&utm_medium=footer)
- [DevOps and Cloud Computing](https://www.scaler.com/devops-course/?utm_source=topics&utm_medium=footer)
- [Neovarsity](https://www.scaler.com/neovarsity/?utm_source=topics&utm_medium=footer)
Explore Topics
- [Free Online Courses](https://www.scaler.com/topics/courses/)
- [Challenges](https://www.scaler.com/topics/challenges/)
- [Contest](https://www.scaler.com/topics/contests/)
- [Topics](https://www.scaler.com/topics/hubs/)
- [Articles](https://www.scaler.com/topics/articles/)
- [Events](https://www.scaler.com/topics/events/)
Resources
- [About Us](https://www.scaler.com/about/?utm_source=topics&utm_medium=footer)
- [Blog](https://www.scaler.com/blog/?utm_source=topics&utm_medium=footer)
- [Careers](https://www.scaler.com/careers/?utm_source=topics&utm_medium=footer)
- [Review](https://www.scaler.com/review/?utm_source=topics&utm_medium=footer)
Download the

app\!
Get all scaler resources under one roof\!
4\.4
1\.71 K Reviews
100K+
Downloads

[](https://app.scaler.com/XBSh)

[](https://app.scaler.com/Yhwr)
Popular Free Certification Courses
[Java Course for Beginners](https://www.scaler.com/topics/course/java-beginners/ "Free Java Course Online")
[C++ Course with Certificate](https://www.scaler.com/topics/course/cpp-beginners/ "Free C++ Course Online")
[Python Course for Beginners](https://www.scaler.com/topics/course/python-for-beginners/ "Free Python Course Online")
[Javascript Free Course for Beginners](https://www.scaler.com/topics/course/javascript-beginners/ "Free Javascript Course Online")
[Data Science Course for Beginners](https://www.scaler.com/topics/course/python-for-data-science/ "Free Data Science Course Online")
[DBMS Course](https://www.scaler.com/topics/course/dbms/ "Free DBMS Course Online")
[Python and SQL for Data Science Course](https://www.scaler.com/topics/course/python-sql-data-science/ "Free Python for Data Science Course Online")
[DSA Problem Solving for Interviews](https://www.scaler.com/topics/course/dsa-interviews-java/ "Free DSA Java Interview Questions Online")
[Instagram System Design Course](https://www.scaler.com/topics/course/instagram-system-design/ "Free Instagram Design Course Online")
[Dynamic Programming Course](https://www.scaler.com/topics/course/dynamic-programming/ "Free Dynamic Programming Course Online")
[All Free Online Courses](https://www.scaler.com/topics/courses/ "All Free Online Courses")
Popular Tutorials
[Python Tutorial](https://www.scaler.com/topics/python/ "Python Tutorial Online")
[Java Tutorial](https://www.scaler.com/topics/java/ "Java Tutorial Online")
[DBMS Tutorial](https://www.scaler.com/topics/dbms/ "DBMS Tutorial Online")
[Javascript Tutorial](https://www.scaler.com/topics/javascript/ "Javascript Tutorial Online")
[C++ Tutorial](https://www.scaler.com/topics/cpp/ "C++ Tutorial Online")
[SQL Tutorial](https://www.scaler.com/topics/sql/ "SQL Tutorial Online")
[Software Engineering Tutorial](https://www.scaler.com/topics/software-engineering/ "Software Engineering Tutorial Online")
[Data Science Tutorial](https://www.scaler.com/topics/data-science/ "Data Science Tutorial Online")
[Pandas Tutorial](https://www.scaler.com/topics/pandas/ "Pandas Tutorial Online")
[Deep Learning Tutorial](https://www.scaler.com/topics/deep-learning/ "Deep Learning Tutorial Online")
[All Tutorials](https://www.scaler.com/topics/hubs/ "All Tutorials")
Compilers
[Python Compiler](https://www.scaler.com/topics/python/online-python-compiler/ "Python Compiler Online")
[Java Compiler](https://www.scaler.com/topics/java/online-java-compiler/ "Java Compiler Online")
[Javascript Compiler](https://www.scaler.com/topics/javascript/online-javascript-compiler/ "Javascript Compiler Online")
[C Compiler](https://www.scaler.com/topics/c/online-c-compiler/ "C Compiler Online")
[C++ Compiler](https://www.scaler.com/topics/cpp/online-cpp-compiler/ "C++ Compiler Online")
Tools
[Json Validator](https://www.scaler.com/topics/javascript/json-validator/ "Json Validator Online")
[SQL Formatter](https://www.scaler.com/topics/sql/sql-formatter/ "SQL Formatter Online")
[XML Formatter](https://www.scaler.com/topics/tools/xml-formatter/ "XML Formatter Online")
[CSS Formatter](https://www.scaler.com/topics/css/css-formatter/ "CSS Formatter Online")
[JavaScript Formatter](https://www.scaler.com/topics/javascript/javascript-formatter/ "JavaScript Formatter Online")
Copyright 2026 InterviewBit Technologies Pvt. Ltd. All Rights Reserved.
[Privacy Policy](https://www.scaler.com/privacy/?utm_source=topics&utm_medium=footer)
[Terms of Use](https://www.scaler.com/terms/?utm_source=topics&utm_medium=footer)
[Contact Us](https://www.scaler.com/contact/?utm_source=topics&utm_medium=footer) |
| Readable Markdown | ## Overview
The Bellman-Ford algorithm is an example of Dynamic Programming. It starts with a starting vertex and calculates the distances of other vertices which can be reached by one edge. It then continues to find a path with two edges and so on. The Bellman-Ford algorithm follows the bottom-up approach.
## What is Bellman-Ford Algorithm?
The **Bellman-Ford algorithm** computes the shortest path from a source vertex to all others in a graph, accommodating both weighted and unweighted edges. While it's generally slower than Dijkstra’s method, Bellman-Ford excels in graphs with negative edge weights and detects negative cycles, a crucial feature. This capability prevents infinite loops where path costs decrease infinitely by traversing negative cycles. Utilizing dynamic programming, Bellman-Ford employs a bottom-up approach, iteratively refining distance estimates via the "Principle of Relaxation." Starting with immediate neighbors, it progressively evaluates longer paths, converging to the optimal solution. However, if negative weight cycles exist, they can distort path distances, necessitating caution during analysis. Thus, Bellman-Ford offers a robust, albeit slower, alternative for diverse graph scenarios.
## Example of Bellman Ford Algorithm
Suppose that we have a graph consisting of 5 vertices having edges between them as shown in the picture below. Now, we want to find shortest distance to each vertex *vi* *0\<i\<6* starting from the vertex 1.

After performing bellman ford algorithm on the above graph the output array would look like - Shortest\_Distance = \[0, 3, 5, 2, 5\]
Where each index 'Ă' of array denotes the shortest distance of the ith vertex from 1st vertex, 1\<=i\<=5.
## How Bellman Ford Algorithm Works?
The algorithm works by iteratively relaxing the edges of the graph to find the shortest path.
Here are the step-by-step workings of the Bellman-Ford algorithm:
**Step 1:** Initialize distances and predecessors
The algorithm starts by initializing the distance of the source node to 0 and the distances of all other nodes in the graph to infinity.
```
```
**Step 2:** Relax edges
The algorithm then iteratively relaxes the edges of the graph. For each edge *u→v* with weight w, it checks if the distance to v can be improved by going through u. If the distance can be improved, it updates the distance of v and sets its predecessor to u.
```
```
Above step is repeated *V-1* times for every edge.
```
```
**Step 3:** Check for negative cycles
After all the edges have been relaxed, the algorithm checks for negative cycles in the graph. A negative cycle is a cycle whose total weight is negative. If there is a negative cycle in the graph, the algorithm reports it and terminates. **Step 2** (relax edges) is repeated one more time for all the edges. If there is some edge some which can be further relaxed then we say that there is an negative cycle present in the graph.
```
```
**Step 4:** Shortest paths
If there are no negative cycles in the graph, the algorithm returns the shortest path from the source node to every other node in the graph.
```
```
### **Input:**
- A 2D Array/List denoting edges and their respective weights.
- A src vertex.
**Output:** An array where each index denotes the shortest path length between that vertex and src vertex.
### Procedure:
1. In this step, we would declare an array of size *V*(Number of vertexes) say *dis\[\]* and initialize with all of its indexes with a very big Value (preferably INT\_MAX) except *src* which will be initialized with value 0. We are doing this because initially we assume that it takes infinite time to reach any of the vertices from our source vertex and we are initializing *dis\[src\]=0* because we are already on source vertex.
2. In this step, the shortest distance is calculated. For it, we would do the underlying step *V-1* times. For every edge *u→v* make *dis\[v\]=min(dis\[u\]+ wt of edge *u→v*, dis\[v\])* It means whenever we are on any vertex *u* we will check if we can reach any of its neighbors in less time it is currently possible to visit, we will update the *dis\[v\]* to *dis\[u\]+wt of edge u→v*.
3. In this step, we will check if there exists a negative edge weight cycle traversing each and every edge *u→v* and checking if there exists *dis\[u\] + wt of edge *u→v* \< dis\[v\]* then our graph contains a negative edge weight cycle because traversing the edges again and again is beneficial as it is lowering the cost to traverse the graph. --\> :::
## Explanation of Bellman Ford Example

***Boost Your Tech Profile! Join Our [DSA Courses](https://www.scaler.com/courses/data-structures-and-algorithms/?utm_source=scaler-topics&utm_medium=bellman-ford-algorithm&utm_campaign=topics-dsa) for Advanced Algorithmic Mastery. Enroll Now to Stand Out in the Coding Landscape\!***
## Difference between Dijkstra's and Bellman Ford's Algorithm
| Bellman Ford Algorithm | Dijkstra Algorithm |
|---|---|
| Its implementation is inspired by the dynamic programming approach. | Its implementation is inspired by the greedy approach. |
| It is easier to implement in a distributive way. | It is quite complex to implement in a distributed way. |
| It also works when the given graph contains a negative edge weight cycle. | It fails if a graph contains a negative edge weight cycle. |
| It's is more time consuming than Dijkstra's. It's Time complexity is O(VE) | It's Time complexity is O(ELogV) |
## Pesudocode
```
```
## Codes Implementation of Bellman Ford Algorithm
- ### C/C++ Implementation of Bellman Ford
```
```
- ### Java Implementation of Bellman Ford
```
```
- ### Python Implementation of Bellman Ford
```
```
## Complexity Analysis of Bellman Ford
> - #### Time Complexity -
>
> Since we are traversing all the edges *V-1* times, and each time we are traversing all the *E* vertices, therefore the time complexity is ***O(V.E)***.
> - #### Space Complexity -
>
> Since we are using an auxiliary array *dis* of size *V*, the space complexity is ***O(V)***.
> Where *V* and *E* are numbers of vertices and edges respectively.
## Bonus Tip of Bellman Ford
The algorithm can be speeded up further because in most of the cases we get our final answer after performing step 2 few times only. Because *dis* array stops getting updated after some steps, So traversing edges again and again is nothing but waste of time.
To check wether any value of *dis* gets updated in any given iteration, we can keep a flag in the outer loop of Step 2 and if it not changed in the inner for loop then we can exit from the loop becuase we have already got our answer.
Though the modification will not change the asymptotic nature of the algorithm because in some graphs we will need all the *V-1* steps to be done. But it will optmize the run time of algorithm in a "average case" i.e. random graphs.
The minor modification need to be done in step 2 is given below -
```
```
Though the average case Time Complexity would be - *O(V.E)* but in the best case it can be done in only *O(E)* time. Think of the case in which we get out of the loop after the very first or second step.
## Applications
- Checking for negative edge weight cycle.
- For finding shortest path of all vertices from single source.
- Routing Algorithms.
***Join our expert-led Dynamic Programming [Free Course](https://www.scaler.com/topics/course/dynamic-programming/) to master advanced problem-solving techniques and enhance your programming prowess.***
## Conclusion
- In this blog, we have discussed one of the most important graph algorithms i.e. Bellman-Ford algorithm which is used to find the shortest path to all vertices from a single source vertex in *O(VE)* time complexity.
- It can find shortest distance of all vertices from single source. It can also detect if there exists a negative edge weight cycle in the given graph. Therefore, it also finds its way in many routing techniques.
- If you want to upskill yourself in Data Structures and algorithms then do checkout, [Scaler](https://www.scaler.com/) where you will get live lectures, assignments, and regular tests from the people working in your dream company. |
| Shard | 103 (laksa) |
| Root Hash | 2748309851778122103 |
| Unparsed URL | com,scaler!www,/topics/data-structures/bellman-ford-algorithm/ s443 |