ℹ️ 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.3 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.algotree.org/algorithms/single_source_shortest_path/bellman_ford_shortest_path/ |
| Last Crawled | 2026-04-09 14:59:50 (7 days ago) |
| First Indexed | 2020-05-20 18:55:01 (5 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Bellman-Ford Shortest Path Algorithm :: AlgoTree |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | The gist of Bellman-Ford single source shortest path algorithm is a below :
Bellman-Ford algorithm finds the shortest path ( in terms of distance / cost ) from a single source in a
directed, weighted graph
containing positive and negative edge weights.
Bellman-Ford algorithm performs edge relaxation of all the edges for every node.
Bellman-Ford Edge Relaxation
If
( distance-from-source-to [ node_v ] > distance-from-source-to [ node_u ] + weight-of-path-from-node-u-to-v )
then
distance-from-source-to [ node_v ] = distance-from-source-to [ node_u ] + weight-of-path-from-node-u-to-v )
With negative edge weights in a graph Bellman-Ford algorithm is preferred over
Dijkstra’s
algorithm as Dijkstra’s algorithm cannot handle negative edge weights in a graph.
Below data structures are used for storing the graph before running Bellman-Ford algorithm
EdgeList
: List of all the edges in the graph.
EdgeWeight
: Map of edges and their corresponding weights.
Algorithm : Bellman-Ford Single Source Shortest Path ( EdgeList, EdgeWeight )
1. Initialize the distance from the source node
S
to all other nodes as infinite (999999999) and to itself as 0.
Distance [ AllNodes ] = 999999999, Distance [
S
] = 0.
2.
For
every node in the graph
3.
For
every edge E in the
EdgeList
4. Node_u = E.first, Node_v = E.second
5. Weight_u_v =
EdgeWeight
( Node_u, Node_v )
6.
If
( Distance [ v ] > Distance [ u ] + Weight_u_v )
7. Distance [ v ] = Distance [ u ] + Weight_u_v
Example of single source shortest path from source node 0 using Bellman-Ford algorithm
Note:
Weight of the path corresponds to the distance / cost between the nodes.
Bellman-Ford iteration 1
Dist [ 0 ] = 0.
Distance from source node 0 to itself is 0.
Dist [ 1 ] = Dist [ 2 ] = Dist [ 3 ] = Dist [ 4 ] = Dist [ 5 ] = 999999999.
Initialize the distance from the source node
0
to all other nodes to a max value (ex:999999999).
Node CountIteration
Edge (U-V)
Weight (Cost/Distance) of Edge (U-V)
Distance from source to node ‘U’
Distance from source to node ‘V’
Update
1
( 0 - 1 )
-1
Dist [ 0 ] = 0
Dist [ 1 ] = 999999999
If : Dist [ 1 ] > Dist [ 0 ] + ( -1 ) Yes
Update : Dist [ 1 ] = 0 + -1 = -1
1
( 0 - 5 )
2
Dist [ 0 ] = 0
Dist [ 5 ] = 999999999
If : Dist [ 5 ] > Dist [ 0 ] + ( 2 ) Yes
Update : Dist [ 5 ] = 0 + 2 = 2
1
( 1 - 2 )
2
Dist [ 1 ] = -1
Dist [ 2 ] = 999999999
If : Dist [ 2 ] > Dist [ 1 ] + ( 2 ) Yes
Update : Dist [ 2 ] = -1 + 2 = 1
1
( 1 - 5 )
-2
Dist [ 1 ] = -1
Dist [ 5 ] = 2
If : Dist [ 5 ] > Dist [ 1 ] + ( -2 ) Yes
Update : Dist [ 5 ] = -1 + -2 = -3
1
( 2 - 3 )
5
Dist [ 2 ] = 1
Dist [ 3 ] = 999999999
If : Dist [ 3 ] > Dist [ 2 ] + ( 5 )Yes
Update : Dist [ 3 ] = 1 + 5 = 6
1
( 2 - 4 )
1
Dist [ 2 ] = 1
Dist [ 4 ] = 999999999
If : Dist [ 4 ] > Dist [ 2 ] + ( 1 )Yes
Update : Dist [ 4 ] = 1 + 1 = 2
1
( 4 - 3 )
-4
Dist [ 4 ] = 2
Dist [ 3 ] = 6
If : Dist [ 3 ] > Dist [ 4 ] + ( -4 )Yes
Update : Dist [ 3 ] = 6 + (-4) = 2
1
( 4 - 5 )
3
Dist [ 4 ] = 2
Dist [ 5 ] = -3
If : Dist [ 5 ] > Dist [ 4 ] + ( 3 )No
No change : Dist [ 5 ] = -3
1
( 5 - 1 )
2
Dist [ 5 ] = -3
Dist [ 1 ] = -1
If : Dist [ 1 ] > Dist [ 5 ] + ( 2 )No
No change : Dist [ 1 ] = -1
1
( 5 - 2 )
3
Dist [ 5 ] = -3
Dist [ 2 ] = 1
If : Dist [ 2 ] > Dist [ 5 ] + ( 3 )Yes
Update Dist [ 2 ] = -3 + 3 = 0
…
the algorithm continues with iterations 2, 3, 4, 5 and 6 (number of nodes). During each iteration the shortest path from source node to other nodes is updated.
Graph type
: Designed for directed graph containing positive and negative edge weights.
Time complexity of Bellman-Ford’s algorithm : O ( E . V )
.
V
is the number of vertices and
E
is the number of edges in a graph.
Bellman-Ford’s shortest implementation
class
Edge
:
def
__init__(self, src, dst, weight) :
self
.
src
=
src
self
.
dst
=
dst
self
.
weight
=
weight
class
Graph
:
def
__init__(self, edge_list, node_cnt) :
self
.
edge_list
=
edge_list
self
.
node_cnt
=
node_cnt
def
BellmanFord
(self, src) :
# Initialize the distance from the source node S to all other nodes as infinite (999999999) and to itself as 0.
distance
=
[
999999999999
]
*
self
.
node_cnt
distance[src]
=
0
for
node
in
range(self
.
node_cnt) :
for
edge
in
self
.
edge_list :
if
(distance[edge
.
dst]
>
distance[edge
.
src]
+
edge
.
weight) :
distance[edge
.
dst]
=
distance[edge
.
src]
+
edge
.
weight
for
edge
in
self
.
edge_list :
if
(distance[edge
.
dst]
>
distance[edge
.
src]
+
edge
.
weight) :
print(
"Negative weight cycle exist in the graph"
)
for
node
in
range(self
.
node_cnt) :
print(
"Source Node("
+
str(src)
+
") -> Destination Node("
+
str(node)
+
") : Length => "
+
str(distance[node]))
def
main
() :
e01
=
Edge(
0
,
1
,
-
1
)
e05
=
Edge(
0
,
5
,
2
)
e12
=
Edge(
1
,
2
,
2
)
e15
=
Edge(
1
,
5
,
-
2
)
e23
=
Edge(
2
,
3
,
5
)
e24
=
Edge(
2
,
4
,
1
)
e43
=
Edge(
4
,
3
,
-
4
)
e45
=
Edge(
4
,
5
,
3
)
e51
=
Edge(
5
,
1
,
2
)
e52
=
Edge(
5
,
2
,
3
)
edge_list
=
[e01, e05, e12, e15, e23, e24, e43, e45, e51, e52]
node_cnt
=
6
source_node
=
0
g
=
Graph(edge_list, node_cnt)
g
.
BellmanFord(source_node)
if
__name__
==
"__main__"
:
main()
Output
Source Node(0) -> Destination Node(0) : Length => 0
Source Node(0) -> Destination Node(1) : Length => -1
Source Node(0) -> Destination Node(2) : Length => 0
Source Node(0) -> Destination Node(3) : Length => -3
Source Node(0) -> Destination Node(4) : Length => 1
Source Node(0) -> Destination Node(5) : Length => -3
#include<iostream>
#include<vector>
#include<list>
using
namespace
std;
class
Edge
{
public
:
Edge(
int
arg_src,
int
arg_dst,
int
arg_weight)
:
src(arg_src), dst(arg_dst), weight(arg_weight)
{}
int
src;
int
dst;
int
weight;
};
class
Graph
{
private
:
int
node_count;
list
<
Edge
>
edge_list;
public
:
Graph (
int
arg_node_count, list
<
Edge
>
arg_edge_list)
:
node_count(arg_node_count), edge_list(arg_edge_list)
{}
void
BellmanFord
(
int
src) {
// Initialize the distance / cost from the source node to all other nodes to some max value.
vector
<
int
>
distance(node_count,
999999999
);
// Distance/cost from the source node to itself is 0.
distance[src]
=
0
;
for
(
int
i
=
0
; i
<
node_count; i
++
) {
for
(
auto
&
it : edge_list) {
if
(distance[it.dst]
>
distance[it.src]
+
it.weight) {
distance[it.dst]
=
distance[it.src]
+
it.weight;
}
}
}
for
(
auto
&
it : edge_list) {
if
(distance[it.dst]
>
distance[it.src]
+
it.weight) {
cout
<<
"Negative weight cycle exist in the graph !!!"
<<
endl;
}
}
for
(
int
i
=
0
; i
<
node_count; i
++
)
cout
<<
"Source Node("
<<
src
<<
") -> Destination Node("
<<
i
<<
") : Length => "
<<
distance[i]
<<
endl;
}
};
int
main
(){
Edge e01(
0
,
1
,
-
1
);
Edge e05(
0
,
5
,
2
);
Edge e12(
1
,
2
,
2
);
Edge e15(
1
,
5
,
-
2
);
Edge e23(
2
,
3
,
5
);
Edge e24(
2
,
4
,
1
);
Edge e43(
4
,
3
,
-
4
);
Edge e45(
4
,
5
,
3
);
Edge e51(
5
,
1
,
2
);
Edge e52(
5
,
2
,
3
);
int
node_count
=
6
;
int
source_node
=
0
;
list
<
Edge
>
edge_list
=
{ e01, e05, e12, e15, e23, e24, e43, e45, e51, e52 };
Graph g(node_count, edge_list);
g.BellmanFord(source_node);
return
0
;
}
Output
Source Node(0) -> Destination Node(0) : Length => 0
Source Node(0) -> Destination Node(1) : Length => -1
Source Node(0) -> Destination Node(2) : Length => 0
Source Node(0) -> Destination Node(3) : Length => -3
Source Node(0) -> Destination Node(4) : Length => 1
Source Node(0) -> Destination Node(5) : Length => -3
import
java.util.ArrayList;
import
java.util.List;
import
java.util.Collections;
class
Edge
{
Edge(
int
arg_src,
int
arg_dst,
int
arg_weight) {
this
.
src
=
arg_src;
this
.
dst
=
arg_dst;
this
.
weight
=
arg_weight;
}
int
src;
int
dst;
int
weight;
}
class
Graph
{
int
node_count;
List
<
Edge
>
edge_list;
Graph (
int
arg_node_count, List
<
Edge
>
arg_edge_list) {
this
.
node_count
=
arg_node_count;
this
.
edge_list
=
arg_edge_list;
}
void
BellmanFord
(
int
src) {
// Initialize the distance/cost from the source node to all other nodes to some max value.
Long INF
=
(
long
) 999999999;
List
<
Long
>
distance
=
new
ArrayList
<
Long
>
(Collections.
nCopies
(node_count, INF));
// Distance/cost from the source node to itself is 0.
distance.
set
(src, (
long
) 0);
for
(
int
i
=
0; i
<
node_count; i
++
) {
for
(Edge it : edge_list) {
if
(distance.
get
(it.
dst
)
>
distance.
get
(it.
src
)
+
it.
weight
) {
distance.
set
(it.
dst
, distance.
get
(it.
src
)
+
it.
weight
);
}
}
}
for
(Edge it : edge_list) {
if
(distance.
get
(it.
dst
)
>
distance.
get
(it.
src
)
+
it.
weight
) {
System.
out
.
println
(
"Negative weight cycle exist in the graph !!!"
);
}
}
for
(
int
i
=
0; i
<
node_count; i
++
)
System.
out
.
println
(
"Source Node("
+
src
+
") -> Destination Node("
+
i
+
") : Length => "
+
distance.
get
(i));
}
public
static
void
main
(String
[]
args) {
Edge e01
=
new
Edge(0, 1,
-
1);
Edge e05
=
new
Edge(0, 5, 2);
Edge e12
=
new
Edge(1, 2, 2);
Edge e15
=
new
Edge(1, 5,
-
2);
Edge e23
=
new
Edge(2, 3, 5);
Edge e24
=
new
Edge(2, 4, 1);
Edge e43
=
new
Edge(4, 3,
-
4);
Edge e45
=
new
Edge(4, 5, 3);
Edge e51
=
new
Edge(5, 1, 2);
Edge e52
=
new
Edge(5, 2, 3);
int
node_count
=
6;
int
source_node
=
0;
List
<
Edge
>
edge_list
=
new
ArrayList
<>
();
Collections.
addAll
(edge_list, e01, e05, e12, e15, e23, e24, e43, e45, e51, e52);
Graph g
=
new
Graph(node_count, edge_list);
g.
BellmanFord
(source_node);
}
}
Output
Source Node(0) -> Destination Node(0) : Length => 0
Source Node(0) -> Destination Node(1) : Length => -1
Source Node(0) -> Destination Node(2) : Length => 0
Source Node(0) -> Destination Node(3) : Length => -3
Source Node(0) -> Destination Node(4) : Length => 1
Source Node(0) -> Destination Node(5) : Length => -3
© 2019-2026 Algotree.org
| All rights reserved.
This content is provided for educational purposes. Feel free to learn, practice, and share knowledge.
For questions or contributions, visit
algotree.org
"First, solve the problem. Then, write the code. - John Johnson" |
| Markdown | **AlgoTree**
- [Home](https://www.algotree.org/)
- [Algorithms](https://www.algotree.org/algorithms/)
- [Sorting Algorithms](https://www.algotree.org/algorithms/sorting/)
- [Merge Sort](https://www.algotree.org/algorithms/sorting/mergesort/)
- [QuickSort](https://www.algotree.org/algorithms/sorting/quicksort/)
- [Binary Search](https://www.algotree.org/algorithms/binary_search/)
- [Searching a number in a 2D Sorted Matrix](https://www.algotree.org/algorithms/binary_search/search_an_element_in_2d_sorted_matrix/)
- [Binary Search : Counting Duplicates 🤡 🤡](https://www.algotree.org/algorithms/binary_search/duplicates/)
- [Binary Search : Finding Square Root √](https://www.algotree.org/algorithms/binary_search/squareroot/)
- [Smallest Number In A Rotated Sorted Array](https://www.algotree.org/algorithms/binary_search/smallest_number_in_a_rotated_sorted_array/)
- [Search Number In A Rotated Sorted Array ↻](https://www.algotree.org/algorithms/binary_search/search_number_in_a_rotated_sorted_array/)
- [Binary Search : Allocate books 📚](https://www.algotree.org/algorithms/binary_search/allot_books/)
- [Binary Search : Ship packages 🚢](https://www.algotree.org/algorithms/binary_search/ship_packages/)
- [Range Minimum Queries ( RMQ ) : Sparse Table](https://www.algotree.org/algorithms/sparse_table/)
- [Binary Indexed Tree ( Fenwick Tree ) 🗂](https://www.algotree.org/algorithms/binary_indexed_trees/)
- [Adjacency Lists](https://www.algotree.org/algorithms/adjacency_list/)
- [\[ C++ \] : Storing Graph As An Adjacency List](https://www.algotree.org/algorithms/adjacency_list/graph_as_adjacency_list_c++/)
- [\[ Java \] : Storing Graph As An Adjacency List](https://www.algotree.org/algorithms/adjacency_list/graph_as_adjacency_list_java/)
- [\[ Python \] : Storing Graph As An Adjacency List](https://www.algotree.org/algorithms/adjacency_list/graph_as_adjacency_list_python/)
- [Tree & Graph Traversals](https://www.algotree.org/algorithms/tree_graph_traversal/)
- [Pre-Order, In-Order & Post-Order Traversals](https://www.algotree.org/algorithms/tree_graph_traversal/pre_in_post_order/)
- [In-Order & Pre-Order : Construct Binary Tree](https://www.algotree.org/algorithms/tree_graph_traversal/construct_tree_from_inorder_preorder/)
- [In-Order & Post-Order : Construct Binary Tree](https://www.algotree.org/algorithms/tree_graph_traversal/construct_tree_from_inorder_postorder/)
- [Level Order Tree Traversal](https://www.algotree.org/algorithms/tree_graph_traversal/level_order/)
- [Right View Of A Binary Tree 🌲 ←](https://www.algotree.org/algorithms/tree_graph_traversal/right_view_of_a_binary_tree/)
- [Level Order : Sum Of The Deepest Leaves](https://www.algotree.org/algorithms/tree_graph_traversal/deepest_leaves_sum/)
- [Top View Of A Binary Tree](https://www.algotree.org/algorithms/tree_graph_traversal/top_view_of_binary_tree/)
- [Balance Binary Search Tree ⚖](https://www.algotree.org/algorithms/tree_graph_traversal/balancing_binary_search_tree/)
- [Level Order : Minimum Depth Of A Binary Tree](https://www.algotree.org/algorithms/tree_graph_traversal/minimum_depth_of_a_binary_tree/)
- [Breadth First Search ( BFS )](https://www.algotree.org/algorithms/tree_graph_traversal/breadth_first_search/)
- [BFS : Finding Max Area Of An Island](https://www.algotree.org/algorithms/tree_graph_traversal/breadth_first_search/max_area_of_island/)
- [BFS : Finding The Number Of Islands 🏝 🏝](https://www.algotree.org/algorithms/tree_graph_traversal/breadth_first_search/finding_number_of_islands/)
- [Depth First Search ( DFS )](https://www.algotree.org/algorithms/tree_graph_traversal/depth_first_search/)
- [DFS : Finding Longest Path In A Tree](https://www.algotree.org/algorithms/tree_graph_traversal/depth_first_search/longest_path_in_a_tree/)
- [DFS : All Paths In A Directed Acyclic Graph](https://www.algotree.org/algorithms/tree_graph_traversal/depth_first_search/all_paths_in_a_graph/)
- [DFS : Detecting Cycle In A Directed Graph ➰](https://www.algotree.org/algorithms/tree_graph_traversal/depth_first_search/cycle_detection_in_directed_graphs/)
- [DFS : Detecting Cycle In An Undirected Graph](https://www.algotree.org/algorithms/tree_graph_traversal/depth_first_search/cycle_detection_in_undirected_graphs/)
- [Topological Sort](https://www.algotree.org/algorithms/tree_graph_traversal/topological_sort/)
- [\[ C++ \] : Lexical Topological Sort](https://www.algotree.org/algorithms/tree_graph_traversal/lexical_topological_sort_c++/)
- [\[ Python \] : Lexical Topological Sort](https://www.algotree.org/algorithms/tree_graph_traversal/lexical_topological_sort_python/)
- [Finding A Binary Subtree In A Tree](https://www.algotree.org/algorithms/tree_graph_traversal/finding_binary_subtree/)
- [Finding Diameter of a Binary Tree](https://www.algotree.org/algorithms/tree_graph_traversal/finding_diameter_of_a_binary_tree/)
- [Deleting Leaf Nodes In A Binary Tree](https://www.algotree.org/algorithms/tree_graph_traversal/deleting_leaf_nodes_in_a_binary_tree/)
- [Merging Binary Trees](https://www.algotree.org/algorithms/tree_graph_traversal/merging_binary_trees/)
- [Binary Search Tree](https://www.algotree.org/algorithms/tree_graph_traversal/binary_search_tree/)
- [Searching A Binary Search Tree](https://www.algotree.org/algorithms/tree_graph_traversal/binary_search_tree/search_a_binary_search_tree/)
- [Validating A Binary Search Tree](https://www.algotree.org/algorithms/tree_graph_traversal/binary_search_tree/validating_a_binary_search_tree/)
- [Inserting Into A Binary Search Tree](https://www.algotree.org/algorithms/tree_graph_traversal/binary_search_tree/inserting_into_a_binary_search_tree/)
- [Height-Balanced Tree Check Using Recursion](https://www.algotree.org/algorithms/tree_graph_traversal/recursively_checking_height_balanced_tree/)
- [Height-Balanced Tree Check Using Traversal](https://www.algotree.org/algorithms/tree_graph_traversal/tree_traversal_check_height_balanced/)
- [Heap](https://www.algotree.org/algorithms/heap/)
- [\[ C++ \] : Max & Min Heap ( Priority Queue / Set )](https://www.algotree.org/algorithms/heap/maxheap_minheap_c++/)
- [\[ Python \] : Max & Min Heap ( HeapQ )](https://www.algotree.org/algorithms/heap/maxheap_minheap_python/)
- [K Most Frequent Elements In An Array](https://www.algotree.org/algorithms/heap/k_most_frequent_array_elements/)
- [K'th largest and smallest element in an array](https://www.algotree.org/algorithms/heap/kth_largest_and_smallest_element_in_array/)
- [Merge K Sorted Linked Lists](https://www.algotree.org/algorithms/heap/merge_k_sorted_linked_lists/)
- [Stack](https://www.algotree.org/algorithms/stack_based/)
- [Expression Conversion : Infix To Postfix](https://www.algotree.org/algorithms/stack_based/infix_to_postfix/)
- [Evaluating An Infix Expression](https://www.algotree.org/algorithms/stack_based/evaluate_infix/)
- [Largest Rectangle In A Histogram 📊](https://www.algotree.org/algorithms/stack_based/largest_rectangle_in_histogram/)
- [Max Size 1 Filled Rectangle In A Binary Matrix](https://www.algotree.org/algorithms/stack_based/maximum_size_rectangle_in_a_binary_matrix/)
- [Stock Span Problem 📈](https://www.algotree.org/algorithms/stack_based/stock_span_problem/)
- [Longest Valid Parentheses](https://www.algotree.org/algorithms/stack_based/longest_valid_parentheses/)
- [Hash Table & Set](https://www.algotree.org/algorithms/hash_table_and_set/)
- [Finding Anagrams](https://www.algotree.org/algorithms/hash_table_and_set/finding_anagrams/)
- [Grouping Anagrams](https://www.algotree.org/algorithms/hash_table_and_set/grouping_anagrams/)
- [Longest Substring w/o Repeating Characters](https://www.algotree.org/algorithms/hash_table_and_set/substring_without_repeating_characters/)
- [Linked List 🔗🔗🔗🔗](https://www.algotree.org/algorithms/linkedlists/)
- [Singly Linked List : Insert & Append](https://www.algotree.org/algorithms/linkedlists/single_linked_list_insert_and_append/)
- [Singly Linked List : Reverse](https://www.algotree.org/algorithms/linkedlists/single_linked_list_reverse/)
- [Singly Linked List : Detect Cycle](https://www.algotree.org/algorithms/linkedlists/singly_linked_list_detect_cycle/)
- [Singly Linked List : Remove Duplicates](https://www.algotree.org/algorithms/linkedlists/remove_duplicates_from_sorted_linked_list/)
- [Doubly Linked List : Insert, Append & Delete](https://www.algotree.org/algorithms/linkedlists/doubly_linked_list/)
- [Backtracking](https://www.algotree.org/algorithms/backtracking/)
- [N Queens problem ♛ ♛ ♛ ♛ ♛ ♛ ♛ ♛](https://www.algotree.org/algorithms/backtracking/nqueens/)
- [Backtracking + DFS : A Game Of Boggle](https://www.algotree.org/algorithms/backtracking/boggle/)
- [Letter Phone 📱](https://www.algotree.org/algorithms/backtracking/letter_phone/)
- [Generating Integer Partitions](https://www.algotree.org/algorithms/backtracking/integer_partitions/)
- [Partition N Elements Into K Non-Empty Subsets](https://www.algotree.org/algorithms/backtracking/partition_n_elements_into_k_nonempty_subsets/)
- [Palindrome Partitioning](https://www.algotree.org/algorithms/backtracking/palindrome_partitioning/)
- [Break a string into a given set of words](https://www.algotree.org/algorithms/backtracking/word_break/)
- [Greedy](https://www.algotree.org/algorithms/greedy/)
- [Light Bulbs 💡 💡 💡 💡 💡](https://www.algotree.org/algorithms/greedy/light_bulbs/)
- [Disjoint-Set : Union By Rank, Path Compression](https://www.algotree.org/algorithms/disjoint_set/)
- [Lowest Common Ancestor ( LCA )](https://www.algotree.org/algorithms/lowest_common_ancestor/)
- [Finding The LCA Using Recursion](https://www.algotree.org/algorithms/lowest_common_ancestor/lca_recursive/)
- [Finding The LCA Using Upward Traversals](https://www.algotree.org/algorithms/lowest_common_ancestor/lca_upwardtraversal/)
- [Finding The LCA By Moving Level Up And Closer](https://www.algotree.org/algorithms/lowest_common_ancestor/lca_hopandmovecloser/)
- [Minimum Spanning Tree Algorithms](https://www.algotree.org/algorithms/minimum_spanning_tree/)
- [\[ Python \] : Prim's Minimum Spanning Tree](https://www.algotree.org/algorithms/minimum_spanning_tree/prims_python/)
- [\[ Java \] : Prim's Minimum Spanning Tree](https://www.algotree.org/algorithms/minimum_spanning_tree/prims_java/)
- [\[ C++ \] : Prim's Minimum Spanning Tree](https://www.algotree.org/algorithms/minimum_spanning_tree/prims_c++/)
- [Kruskal's Minimum Spanning Tree](https://www.algotree.org/algorithms/minimum_spanning_tree/kruskals/)
- [Single Source Shortest Path Algorithms](https://www.algotree.org/algorithms/single_source_shortest_path/)
- [\[ Python \] : Dijkstra's Shortest Path](https://www.algotree.org/algorithms/single_source_shortest_path/dijkstras_shortest_path_python/)
- [\[ C++ \] : Dijkstra's Shortest Path](https://www.algotree.org/algorithms/single_source_shortest_path/dijkstras_shortest_path_c++/)
- [\[ Java \] : Dijkstra's Shortest Path](https://www.algotree.org/algorithms/single_source_shortest_path/dijkstras_shortest_path_java/)
- [Bellman-Ford's Shortest Path Algorithm](https://www.algotree.org/algorithms/single_source_shortest_path/bellman_ford_shortest_path/)
- [Bellman Ford's Algorithm For DAG](https://www.algotree.org/algorithms/single_source_shortest_path/bellman_ford_on_dag/)
- [All Pairs Shortest Path : Floyd-Warshall](https://www.algotree.org/algorithms/floyd-warshall/)
- [Numeric 🔢](https://www.algotree.org/algorithms/numeric/)
- [Fibonacci Sequence 🧬](https://www.algotree.org/algorithms/numeric/fibonacci_sequence/)
- [Euler's Totient Function](https://www.algotree.org/algorithms/numeric/euler_totient/)
- [Prime Sieve : Generating Prime Numbers](https://www.algotree.org/algorithms/numeric/prime_sieve/)
- [Prime Factors](https://www.algotree.org/algorithms/numeric/prime_factors/)
- [Euclid's : Finding The Greatest Common Divisor](https://www.algotree.org/algorithms/numeric/euclid_gcd/)
- [Factorials Of Large Numbers \!](https://www.algotree.org/algorithms/numeric/large_factorials/)
- [Fast Exponentiation](https://www.algotree.org/algorithms/numeric/fast_exponentiation/)
- [Modular Multiplication & Exponentiation](https://www.algotree.org/algorithms/numeric/modular_multiplication_exponentiation/)
- [Prime Or Non Prime ( Miller-Rabin )](https://www.algotree.org/algorithms/numeric/check_if_prime_miller_rabin/)
- [Pythagorean Triples 📐](https://www.algotree.org/algorithms/numeric/pythagorean_triples/)
- [Pythagorean Triples In An Array 📐](https://www.algotree.org/algorithms/numeric/pythagorean_triples_in_an_array/)
- [Binomial Coefficients](https://www.algotree.org/algorithms/numeric/binomial_coefficients/)
- [Subsets / Combinations : Bitwise](https://www.algotree.org/algorithms/numeric/subsets_bitwise/)
- [Subsets Using Permutations](https://www.algotree.org/algorithms/numeric/subsets_next_permutation/)
- [Integer To Hexadecimal Conversion](https://www.algotree.org/algorithms/numeric/integer_to_hex/)
- [Matrix Multiplication](https://www.algotree.org/algorithms/numeric/matrix_multiplication/)
- [Sudoku](https://www.algotree.org/algorithms/sudoku/)
- [Validate A Given Sudoku](https://www.algotree.org/algorithms/sudoku/validate_sudoku/)
- [Computational Geometry](https://www.algotree.org/algorithms/computational_geometry/)
- [Line Segment Intersection](https://www.algotree.org/algorithms/computational_geometry/line_segment_intersection/)
- [Bitwise Operations](https://www.algotree.org/algorithms/bitwise/)
- [Number Of Set Bits In An Integer](https://www.algotree.org/algorithms/bitwise/count_set_bits/)
- [Toggle Last Set Bit](https://www.algotree.org/algorithms/bitwise/toggle_last_set_bit/)
- [Swapping Integers Using Bitwise XOR](https://www.algotree.org/algorithms/bitwise/swap_integers/)
- [Binary To Decimal Conversion](https://www.algotree.org/algorithms/bitwise/binary_to_decimal/)
- [Recursive Algorithms 🌀 🌀 🌀](https://www.algotree.org/algorithms/recursive/)
- [Recursive : Finding the N'th Fibonacci number](https://www.algotree.org/algorithms/recursive/generate_nth_fibonacci_number/)
- [Recursive : Generating Permutations](https://www.algotree.org/algorithms/recursive/permutations_recursion/)
- [Recursive : Generating Subsets / Combinations](https://www.algotree.org/algorithms/recursive/subsets_recursion/)
- [Recursive : Dollar sack 💰💰💰](https://www.algotree.org/algorithms/recursive/dollar_sack/)
- [Recursive : Generating Subsequences](https://www.algotree.org/algorithms/recursive/generate_all_subsequences/)
- [Recursive : Generating All Balanced Parenthesis](https://www.algotree.org/algorithms/recursive/generating_all_balanced_parenthesis/)
- [Recursive : Word Search](https://www.algotree.org/algorithms/recursive/word_search/)
- [Recursive : Tower Of Hanoi 🗼](https://www.algotree.org/algorithms/recursive/tower_of_hanoi/)
- [Recursive : Finding Max Depth Of A Binary Tree](https://www.algotree.org/algorithms/recursive/maximum_depth_of_a_binary_tree/)
- [Cache](https://www.algotree.org/algorithms/cache/)
- [LFU ( Least Frequently Used ) Cache](https://www.algotree.org/algorithms/cache/lfu_cache/)
- [LRU ( Least Recently Used ) Cache](https://www.algotree.org/algorithms/cache/lru_cache/)
- [Dynamic Programming](https://www.algotree.org/algorithms/dynamic_programming/)
- [Longest Common Subsequence 🧬](https://www.algotree.org/algorithms/dynamic_programming/longest_common_subsequence/)
- [Longest Increasing Subsequence 🧬](https://www.algotree.org/algorithms/dynamic_programming/longest_increasing_subsequence/)
- [Distinct Subsequences 🧬](https://www.algotree.org/algorithms/dynamic_programming/distinct_subsequences/)
- [Matrix Chain Multiplication ⛓ ❌ ⛓ ❌ ⛓](https://www.algotree.org/algorithms/dynamic_programming/matrix_chain_multiplication/)
- [Finding Longest Palindromic Substring](https://www.algotree.org/algorithms/dynamic_programming/longest_palindromic_substring/)
- [Minimum Cuts To Make A Palindrome ✂ ✂](https://www.algotree.org/algorithms/dynamic_programming/minimum_cuts_to_make_string_palindrome/)
- [Word Break](https://www.algotree.org/algorithms/dynamic_programming/word_break/)
- [String Interleave](https://www.algotree.org/algorithms/dynamic_programming/string_interleave/)
- [0-1 Knapsack Problem 💰](https://www.algotree.org/algorithms/dynamic_programming/0_1_knapsack/)
- [Coins Change Problem 🪙](https://www.algotree.org/algorithms/dynamic_programming/coins_change/)
- [Minimum Coins For Making Change 💵 🪙](https://www.algotree.org/algorithms/dynamic_programming/minimum_coins_for_change/)
- [Integer Partitioning Problem](https://www.algotree.org/algorithms/dynamic_programming/integer_partitioning/)
- [Subset Sum Problem ⊆](https://www.algotree.org/algorithms/dynamic_programming/subset_sum_problem/)
- [Maximum Product Subarray Problem](https://www.algotree.org/algorithms/dynamic_programming/maximum_product_subarray/)
- [Maximum Sum Subarray Problem](https://www.algotree.org/algorithms/dynamic_programming/maximum_sum_subarray/)
- [Finding Size Of Biggest 1 Filled Square](https://www.algotree.org/algorithms/dynamic_programming/maximal_square/)
- [Maximum Sum SubRectangle](https://www.algotree.org/algorithms/dynamic_programming/maximum_sum_subrectangle/)
- [Using Aggregate Rectangles](https://www.algotree.org/algorithms/dynamic_programming/maximum_sum_subrectangle/aggregate_rectangles/)
- [Applying Kadane's Algorithm On Row Sums](https://www.algotree.org/algorithms/dynamic_programming/maximum_sum_subrectangle/kadane_row_summations/)
- [Unique Paths In A Grid ▦](https://www.algotree.org/algorithms/dynamic_programming/unique_paths_in_a_grid/)
- [Egg Drop Problem 🥚](https://www.algotree.org/algorithms/dynamic_programming/egg_drop/)
- [Assignment Problem Using BitMask](https://www.algotree.org/algorithms/dynamic_programming/assignments_using_bitmask/)
- [Edit Distance](https://www.algotree.org/algorithms/dynamic_programming/edit_distance/)
- [Climbing Stairs Problem 🪜](https://www.algotree.org/algorithms/dynamic_programming/climbing_stairs/)
- [KMP Pattern Match Algorithm](https://www.algotree.org/algorithms/pattern_matching/)
- [Minimum Steps To Make Two Strings Anagrams](https://www.algotree.org/algorithms/minimum_step_to_make_anagrams/)
- [Trie \[ Python \] \[ Java \]](https://www.algotree.org/algorithms/trie_python_java/)
- [Trie \[ C++ \]](https://www.algotree.org/algorithms/trie/)
- [Counting Distinct Substrings](https://www.algotree.org/algorithms/trie/all_substrings/)
- [Solving Boggle Using Trie & Depth First Search](https://www.algotree.org/algorithms/trie/trie_dfs_boggle/)
- [Rubik's Cube](https://www.algotree.org/algorithms/rubik_cube/)
- [Solving a 2 x 2 Rubik's Cube 💠](https://www.algotree.org/algorithms/rubik_cube/solving_2x2_rubik_cube/)
- [Solving a 3 x 3 Rubik's Cube](https://www.algotree.org/algorithms/rubik_cube/solving_3x3_rubik_cube/)
- [A Pinch Of Code](https://www.algotree.org/algorithms/snippets/)
- [Java : List - Create & Initialize](https://www.algotree.org/algorithms/snippets/java_list_create_initialize/)
- [Java : List Of Arrays](https://www.algotree.org/algorithms/snippets/java_list_of_arrays/)
- [Python : Create A Dictionary From A List](https://www.algotree.org/algorithms/snippets/python_create_dictionary_from_list/)
- [Python : Sort Dictionary By Value & Key](https://www.algotree.org/algorithms/snippets/python_sort_dictionary/)
- [Python : Delete Key & Value from Dictionary](https://www.algotree.org/algorithms/snippets/python_delete_key_from_dictionary/)
- [Python : Merge Dictionaries](https://www.algotree.org/algorithms/snippets/python_merge_dictionaries/)
- [Python : Two dimensional list.](https://www.algotree.org/algorithms/snippets/python_two_dimensional_list/)
- [Python : Convert List Of Strings To List Of Int](https://www.algotree.org/algorithms/snippets/python_list_of_strings_to_list_of_int/)
- [Python : Getting Current Date & Time](https://www.algotree.org/algorithms/snippets/python_current_date_time/)
- [Python : Decorators](https://www.algotree.org/algorithms/snippets/python_decorators/)
- [Python : Reading JSON file](https://www.algotree.org/algorithms/snippets/python_reading_json/)
- [Python : Agrument Parser](https://www.algotree.org/algorithms/snippets/python_argument_parser/)
- [Python : First & Last N Characters Of A String](https://www.algotree.org/algorithms/snippets/python_first_and_last_n_characters_of_string/)
- [Go : Check If File Exists](https://www.algotree.org/algorithms/snippets/golang_check_if_file_exists/)
- [Go : Read File Line By Line](https://www.algotree.org/algorithms/snippets/golang_read_file_line_by_line/)
- [Go : Extract Pattern Using Regular Expression](https://www.algotree.org/algorithms/snippets/golang_extract_pattern_using_regexp/)
- [Go : Check If A Key Exists In A Map ( Dict )](https://www.algotree.org/algorithms/snippets/go_check_if_key_exists_in_a_map/)
- [Go : Remove / Hide fields from a struct](https://www.algotree.org/algorithms/snippets/golang_remove_struct_fields/)
- [C++ : Compilation Process](https://www.algotree.org/algorithms/snippets/c++_compilation_process/)
- [C++ : String conversion upper / lower case](https://www.algotree.org/algorithms/snippets/c++_uppercase_lowercase/)
- [C++ : Convert String Of Integers Into A Vector](https://www.algotree.org/algorithms/snippets/c++_convert_string_to_array_of_int/)
- [C++ : Static Keyword](https://www.algotree.org/algorithms/snippets/c++_static_keyword/)
- [C++ : Copy Constructor](https://www.algotree.org/algorithms/snippets/c++_copy_constructor/)
- [C++ : Lvaule and Rvalue](https://www.algotree.org/algorithms/snippets/c++_lvalue_rvalue/)
- [C++ : Move Constructor](https://www.algotree.org/algorithms/snippets/c++_move_constructor/)
- [C++ : Overload Assignment (=) Operator](https://www.algotree.org/algorithms/snippets/c++_overload_assignment_operator/)
- [C++ : Move Assignment Operator](https://www.algotree.org/algorithms/snippets/c++_move_assignment_operator/)
- [C++ : Overload Subscript ( \[ \] ) Operator](https://www.algotree.org/algorithms/snippets/c++_overload_subscript_operator/)
- [C++ : Member Initializer List](https://www.algotree.org/algorithms/snippets/c++_member_initializer_list/)
- [C++ : Singleton Design Pattern](https://www.algotree.org/algorithms/snippets/c++_singleton/)
- [C++ : Templates](https://www.algotree.org/algorithms/snippets/c++_templates/)
- [C++ : static\_cast & dynamic\_cast](https://www.algotree.org/algorithms/snippets/c++_static_dynamic_cast/)
- [C++ : const\_cast & reinterpret\_cast](https://www.algotree.org/algorithms/snippets/c++_const_cast_reinterpret_cast/)
- [C++ : Throwing Exceptions From A Destructor](https://www.algotree.org/algorithms/snippets/c++_throwning_exceptions_from_destructor/)
- [C++ : Lambda Expression & Callback Functions](https://www.algotree.org/algorithms/snippets/c++_lambda_functions_and_callbacks/)
- [C++ : Smart Pointers ( unique, shared, weak )](https://www.algotree.org/algorithms/snippets/c++_smart_pointers/)
- [C++ : Initializing A Vector](https://www.algotree.org/algorithms/snippets/c++_initialize_vector/)
- [C++ : Threads ( Producer & Consumer )](https://www.algotree.org/algorithms/snippets/c++_threads_producer_consumer/)
- [C++ : Threads & Condition Variable 🧵](https://www.algotree.org/algorithms/snippets/c++_threads_conditional_wait/)
- [C++ & Boost : Program Options](https://www.algotree.org/algorithms/snippets/c++_boost_program_options_positional_options/)
- [C++ & Boost : Parsing XML](https://www.algotree.org/algorithms/snippets/c++_boost_parsing_xml/)
- [C++ & Boost : Generating UUID](https://www.algotree.org/algorithms/snippets/c++_boost_uuid/)
- [JavaScript : Remove An Item From An Array](https://www.algotree.org/algorithms/snippets/javascript_remove_specific_item_from_array/)
- [JavaScript : Accept Only A Numeric Input](https://www.algotree.org/algorithms/snippets/javascript_accept_float_input/)
- [JavaScript : Extract Numbers From String](https://www.algotree.org/algorithms/snippets/javascript_extract_numbers_from_string/)
- [About](https://www.algotree.org/about/)
[Algotree](https://www.algotree.org/)
\>
[Algorithms](https://www.algotree.org/algorithms/)
\>
[Single Source Shortest Path](https://www.algotree.org/algorithms/single_source_shortest_path/)
\> Bellman-Ford Shortest Path Algorithm
[Shortest Path](https://www.algotree.org/tags/shortest-path) [Python](https://www.algotree.org/tags/python) [C++](https://www.algotree.org/tags/c++) [Java](https://www.algotree.org/tags/java)
# Bellman-Ford Shortest Path Algorithm
The gist of Bellman-Ford single source shortest path algorithm is a below :
- Bellman-Ford algorithm finds the shortest path ( in terms of distance / cost ) from a single source in a **directed, weighted graph** containing positive and negative edge weights.
- Bellman-Ford algorithm performs edge relaxation of all the edges for every node. **Bellman-Ford Edge Relaxation** **If** ( distance-from-source-to \[ node\_v \] \> distance-from-source-to \[ node\_u \] + weight-of-path-from-node-u-to-v ) **then** distance-from-source-to \[ node\_v \] = distance-from-source-to \[ node\_u \] + weight-of-path-from-node-u-to-v )
- With negative edge weights in a graph Bellman-Ford algorithm is preferred over [**Dijkstra’s**](https://algotree.org/algorithms/single_source_shortest_path/dijkstras_shortest_path/) algorithm as Dijkstra’s algorithm cannot handle negative edge weights in a graph.
***
Below data structures are used for storing the graph before running Bellman-Ford algorithm
- **EdgeList** : List of all the edges in the graph.
- **EdgeWeight** : Map of edges and their corresponding weights.
***
***
**Algorithm : Bellman-Ford Single Source Shortest Path ( EdgeList, EdgeWeight )**
1\. Initialize the distance from the source node **S** to all other nodes as infinite (999999999) and to itself as 0. Distance \[ AllNodes \] = 999999999, Distance \[ **S** \] = 0. 2. **For** every node in the graph 3. **For** every edge E in the **EdgeList** 4. Node\_u = E.first, Node\_v = E.second 5. Weight\_u\_v = **EdgeWeight** ( Node\_u, Node\_v ) 6. **If** ( Distance \[ v \] \> Distance \[ u \] + Weight\_u\_v ) 7. Distance \[ v \] = Distance \[ u \] + Weight\_u\_v
***
**Example of single source shortest path from source node 0 using Bellman-Ford algorithm**
**Note:** Weight of the path corresponds to the distance / cost between the nodes.
**Bellman-Ford iteration 1** **Dist \[ 0 \] = 0.** Distance from source node 0 to itself is 0. **Dist \[ 1 \] = Dist \[ 2 \] = Dist \[ 3 \] = Dist \[ 4 \] = Dist \[ 5 \] = 999999999.** Initialize the distance from the source node **0** to all other nodes to a max value (ex:999999999).
| Node CountIteration | Edge (U-V) | Weight (Cost/Distance) of Edge (U-V) | Distance from source to node ‘U’ | Distance from source to node ‘V’ | Update |
|---|---|---|---|---|---|
| 1 | ( 0 - 1 ) | \-1 | Dist \[ 0 \] = 0 | Dist \[ 1 \] = 999999999 | If : Dist \[ 1 \] \> Dist \[ 0 \] + ( -1 ) Yes **Update : Dist \[ 1 \] = 0 + -1 = -1** |
| 1 | ( 0 - 5 ) | 2 | Dist \[ 0 \] = 0 | Dist \[ 5 \] = 999999999 | If : Dist \[ 5 \] \> Dist \[ 0 \] + ( 2 ) Yes **Update : Dist \[ 5 \] = 0 + 2 = 2** |
| 1 | ( 1 - 2 ) | 2 | Dist \[ 1 \] = -1 | Dist \[ 2 \] = 999999999 | If : Dist \[ 2 \] \> Dist \[ 1 \] + ( 2 ) Yes **Update : Dist \[ 2 \] = -1 + 2 = 1** |
| 1 | ( 1 - 5 ) | \-2 | Dist \[ 1 \] = -1 | Dist \[ 5 \] = 2 | If : Dist \[ 5 \] \> Dist \[ 1 \] + ( -2 ) Yes **Update : Dist \[ 5 \] = -1 + -2 = -3** |
| 1 | ( 2 - 3 ) | 5 | Dist \[ 2 \] = 1 | Dist \[ 3 \] = 999999999 | If : Dist \[ 3 \] \> Dist \[ 2 \] + ( 5 )Yes **Update : Dist \[ 3 \] = 1 + 5 = 6** |
| 1 | ( 2 - 4 ) | 1 | Dist \[ 2 \] = 1 | Dist \[ 4 \] = 999999999 | If : Dist \[ 4 \] \> Dist \[ 2 \] + ( 1 )Yes **Update : Dist \[ 4 \] = 1 + 1 = 2** |
| 1 | ( 4 - 3 ) | \-4 | Dist \[ 4 \] = 2 | Dist \[ 3 \] = 6 | If : Dist \[ 3 \] \> Dist \[ 4 \] + ( -4 )Yes **Update : Dist \[ 3 \] = 6 + (-4) = 2** |
| 1 | ( 4 - 5 ) | 3 | Dist \[ 4 \] = 2 | Dist \[ 5 \] = -3 | If : Dist \[ 5 \] \> Dist \[ 4 \] + ( 3 )No **No change : Dist \[ 5 \] = -3** |
| 1 | ( 5 - 1 ) | 2 | Dist \[ 5 \] = -3 | Dist \[ 1 \] = -1 | If : Dist \[ 1 \] \> Dist \[ 5 \] + ( 2 )No **No change : Dist \[ 1 \] = -1** |
| 1 | ( 5 - 2 ) | 3 | Dist \[ 5 \] = -3 | Dist \[ 2 \] = 1 | If : Dist \[ 2 \] \> Dist \[ 5 \] + ( 3 )Yes **Update Dist \[ 2 \] = -3 + 3 = 0** |
… the algorithm continues with iterations 2, 3, 4, 5 and 6 (number of nodes). During each iteration the shortest path from source node to other nodes is updated.

**Graph type** : Designed for directed graph containing positive and negative edge weights. **Time complexity of Bellman-Ford’s algorithm : O ( E . V )**. **V** is the number of vertices and **E** is the number of edges in a graph.
***
***
**Bellman-Ford’s shortest implementation**
Python
C++
Java
```
class Edge :
def __init__(self, src, dst, weight) :
self.src = src
self.dst = dst
self.weight = weight
class Graph :
def __init__(self, edge_list, node_cnt) :
self.edge_list = edge_list
self.node_cnt = node_cnt
def BellmanFord (self, src) :
# Initialize the distance from the source node S to all other nodes as infinite (999999999) and to itself as 0.
distance = [999999999999] * self.node_cnt
distance[src] = 0
for node in range(self.node_cnt) :
for edge in self.edge_list :
if (distance[edge.dst] > distance[edge.src] + edge.weight) :
distance[edge.dst] = distance[edge.src] + edge.weight
for edge in self.edge_list :
if (distance[edge.dst] > distance[edge.src] + edge.weight) :
print("Negative weight cycle exist in the graph")
for node in range(self.node_cnt) :
print("Source Node("+str(src)+") -> Destination Node("+str(node)+") : Length => "+str(distance[node]))
def main() :
e01 = Edge(0, 1, -1)
e05 = Edge(0, 5, 2)
e12 = Edge(1, 2, 2)
e15 = Edge(1, 5, -2)
e23 = Edge(2, 3, 5)
e24 = Edge(2, 4, 1)
e43 = Edge(4, 3, -4)
e45 = Edge(4, 5, 3)
e51 = Edge(5, 1, 2)
e52 = Edge(5, 2, 3)
edge_list = [e01, e05, e12, e15, e23, e24, e43, e45, e51, e52]
node_cnt = 6
source_node = 0
g = Graph(edge_list, node_cnt)
g.BellmanFord(source_node)
if __name__ == "__main__":
main()
```
Output
```
Source Node(0) -> Destination Node(0) : Length => 0
Source Node(0) -> Destination Node(1) : Length => -1
Source Node(0) -> Destination Node(2) : Length => 0
Source Node(0) -> Destination Node(3) : Length => -3
Source Node(0) -> Destination Node(4) : Length => 1
Source Node(0) -> Destination Node(5) : Length => -3
```
```
#include<iostream>
#include<vector>
#include<list>
using namespace std;
class Edge {
public :
Edge(int arg_src, int arg_dst, int arg_weight) : src(arg_src), dst(arg_dst), weight(arg_weight)
{}
int src;
int dst;
int weight;
};
class Graph {
private :
int node_count;
list<Edge> edge_list;
public:
Graph (int arg_node_count, list<Edge> arg_edge_list) : node_count(arg_node_count), edge_list(arg_edge_list)
{}
void BellmanFord (int src) {
// Initialize the distance / cost from the source node to all other nodes to some max value.
vector<int> distance(node_count, 999999999);
// Distance/cost from the source node to itself is 0.
distance[src] = 0;
for (int i=0; i<node_count; i++) {
for (auto& it : edge_list) {
if (distance[it.dst] > distance[it.src] + it.weight) {
distance[it.dst] = distance[it.src] + it.weight;
}
}
}
for (auto& it : edge_list) {
if (distance[it.dst] > distance[it.src] + it.weight) {
cout << "Negative weight cycle exist in the graph !!!" << endl;
}
}
for (int i=0; i<node_count; i++)
cout << "Source Node(" << src << ") -> Destination Node(" << i << ") : Length => " << distance[i] << endl;
}
};
int main(){
Edge e01(0, 1, -1);
Edge e05(0, 5, 2);
Edge e12(1, 2, 2);
Edge e15(1, 5, -2);
Edge e23(2, 3, 5);
Edge e24(2, 4, 1);
Edge e43(4, 3, -4);
Edge e45(4, 5, 3);
Edge e51(5, 1, 2);
Edge e52(5, 2, 3);
int node_count = 6;
int source_node = 0;
list<Edge> edge_list = { e01, e05, e12, e15, e23, e24, e43, e45, e51, e52 };
Graph g(node_count, edge_list);
g.BellmanFord(source_node);
return 0;
}
```
Output
```
Source Node(0) -> Destination Node(0) : Length => 0
Source Node(0) -> Destination Node(1) : Length => -1
Source Node(0) -> Destination Node(2) : Length => 0
Source Node(0) -> Destination Node(3) : Length => -3
Source Node(0) -> Destination Node(4) : Length => 1
Source Node(0) -> Destination Node(5) : Length => -3
```
```
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
class Edge {
Edge(int arg_src, int arg_dst, int arg_weight) {
this.src = arg_src;
this.dst = arg_dst;
this.weight = arg_weight;
}
int src;
int dst;
int weight;
}
class Graph {
int node_count;
List<Edge> edge_list;
Graph (int arg_node_count, List<Edge> arg_edge_list) {
this.node_count = arg_node_count;
this.edge_list = arg_edge_list;
}
void BellmanFord (int src) {
// Initialize the distance/cost from the source node to all other nodes to some max value.
Long INF = (long) 999999999;
List<Long> distance = new ArrayList<Long>(Collections.nCopies(node_count, INF));
// Distance/cost from the source node to itself is 0.
distance.set(src, (long) 0);
for (int i=0; i<node_count; i++) {
for (Edge it : edge_list) {
if (distance.get(it.dst) > distance.get(it.src) + it.weight) {
distance.set(it.dst, distance.get(it.src) + it.weight);
}
}
}
for (Edge it : edge_list) {
if (distance.get(it.dst) > distance.get(it.src) + it.weight) {
System.out.println("Negative weight cycle exist in the graph !!!");
}
}
for (int i=0; i<node_count; i++)
System.out.println("Source Node(" + src + ") -> Destination Node(" + i + ") : Length => " + distance.get(i));
}
public static void main (String[] args) {
Edge e01 = new Edge(0, 1, -1);
Edge e05 = new Edge(0, 5, 2);
Edge e12 = new Edge(1, 2, 2);
Edge e15 = new Edge(1, 5, -2);
Edge e23 = new Edge(2, 3, 5);
Edge e24 = new Edge(2, 4, 1);
Edge e43 = new Edge(4, 3, -4);
Edge e45 = new Edge(4, 5, 3);
Edge e51 = new Edge(5, 1, 2);
Edge e52 = new Edge(5, 2, 3);
int node_count = 6;
int source_node = 0;
List<Edge> edge_list = new ArrayList<>();
Collections.addAll(edge_list, e01, e05, e12, e15, e23, e24, e43, e45, e51, e52);
Graph g = new Graph(node_count, edge_list);
g.BellmanFord(source_node);
}
}
```
Output
```
Source Node(0) -> Destination Node(0) : Length => 0
Source Node(0) -> Destination Node(1) : Length => -1
Source Node(0) -> Destination Node(2) : Length => 0
Source Node(0) -> Destination Node(3) : Length => -3
Source Node(0) -> Destination Node(4) : Length => 1
Source Node(0) -> Destination Node(5) : Length => -3
```
***
***
**© 2019-2026 Algotree.org** \| All rights reserved.
This content is provided for educational purposes. Feel free to learn, practice, and share knowledge.
For questions or contributions, visit [algotree.org](https://algotree.org/)
"First, solve the problem. Then, write the code. - John Johnson" |
| Readable Markdown | null |
| Shard | 174 (laksa) |
| Root Hash | 15388939227391360774 |
| Unparsed URL | org,algotree!www,/algorithms/single_source_shortest_path/bellman_ford_shortest_path/ s443 |