🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 79 (from laksa184)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

📄
INDEXABLE
CRAWLED
7 hours ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm
Last Crawled2026-04-13 02:16:37 (7 hours ago)
First Indexed2021-11-25 14:07:19 (4 years ago)
HTTP Status Code200
Meta TitleBellman-Ford Algorithm: Pseudocode, Time Complexity and Examples | Simplilearn
Meta DescriptionExplore what the Bellman Ford algorithm is and how it works. Learn to understand the pseudocode, time complexity for applying the algorithm and the applications and uses.
Meta Canonicalnull
Boilerpipe Text
The Bellman-Ford algorithm emulates the shortest paths from a single source vertex to all other vertices in a weighted digraph. It is slower than Dijkstra's algorithm for the same problem but more versatile because it can handle graphs with some edge weights that are negative numbers. Alfonso Shimbel proposed the algorithm in 1955, but it is now named after Richard Bellman and Lester Ford Jr., who brought it out in 1958 and 1956. In 1959, Edward F. Moore published a variation of the algorithm , sometimes referred to as the Bellman-Ford–Moore algorithm. What Is the Bellman-Ford Algorithm? Dynamic Programming is used in the Bellman-Ford algorithm. It begins with a starting vertex and calculates the distances between other vertices that a single edge can reach. It then searches for a path with two edges, and so on. The Bellman-Ford algorithm uses the bottom-up approach. Based on the "Principle of Relaxation," more accurate values gradually recovered an approximation to the proper distance until finally reaching the optimum solution. Negative weight edges can generate negative weight cycles, which reduce the total path distance by returning to the same point. Why Should You Be Cautious With Negative Weights? When attempting to find the shortest path, negative weight cycles may produce an incorrect result. Shortest path algorithms, such as Dijkstra's Algorithm that cannot detect such a cycle, may produce incorrect results because they may go through a negative weight cycle, reducing the path length. After learning about the Bellman-Ford algorithm, you will look at how it works in this tutorial. How Does the Bellman-Ford Algorithm Work? The Bellman-Ford algorithm works by grossly underestimating the length of the path from the starting vertex to all other vertices. The algorithm then iteratively relaxes those estimates by discovering new ways that are shorter than the previously overestimated paths. You can ensure that the result is optimized by repeating this process for all vertices. Step 1: Make a list of all the graph's edges. This is simple if an adjacency list represents the graph. Step 2: "V - 1" is used to calculate the number of iterations. Because the shortest distance to an edge can be adjusted V - 1 time at most, the number of iterations will increase the same number of vertices. Step 3: Begin with an arbitrary vertex and a minimum distance of zero. Because you are exaggerating the actual distances, all other nodes should be assigned infinity. For each edge u-v, relax the path lengths for the vertices: If distance[v] is greater than distance[u] + edge weight uv, then distance[v] = distance[u] + edge weight uv Step 4:If the new distance is less than the previous one, update the distance for each Edge in each iteration. The distance to each node is the total distance from the starting node to this specific node. Step 5: To ensure that all possible paths are considered, you must consider alliterations. You will end up with the shortest distance if you do this. Moving ahead with this tutorial on the Bellman-Ford algorithm, you will now learn the pseudocode for this algorithm. Pseudocode of the Bellman-Ford Algorithm Every Vertex's path distance must be maintained. That can be stored in a V-dimensional array, where V is the number of vertices. Not only do you need to know the length of the shortest path, but you also need to be able to find it. To accomplish this, you must map each Vertex to the Vertex that most recently updated its path length. When the algorithm is finished, you can find the path from the destination vertex to the source. function bellmanFordAlgorithm(G, s) //G is the graph and s is the source vertex   for each vertex V in G     dist[V] <- infinite // dist is distance       prev[V] <- NULL // prev is previous   dist[s] <- 0   for each vertex V in G     for each edge (u,v) in G       temporaryDist <- dist[u] + edgeweight(u, v)       if temporaryDist < dist[v]         dist[v] <- temporaryDist         prev[v] <- u    for each edge (U,V) in G     If dist[U] + edgeweight(U, V) < dist[V}       Error: Negative Cycle Exists   return dist[], previ[] As you progress through this tutorial, you will see an example of the Bellman-Ford algorithm for a better learning experience. An Example of Bellman-Ford Algorithm Consider the weighted graph below. Choose path value 0 for the source vertex and infinity for all other vertices. If the new calculated path length is less than the previous path length, go to the source vertex's neighboring Edge and relax the path length of the adjacent Vertex. This procedure must be repeated V-1 times, where V is the number of vertices in total. This happened because, in the worst-case scenario, any vertex's path length can be changed N times to an even shorter path length. As a result, after V-1 iterations, you find your new path lengths and can determine in case the graph has a negative cycle or not. You will now look at the time and space complexity of the Bellman-Ford algorithm after you have a better understanding of it. The Complexity of Bellman-Ford Algorithm Following is the time complexity of the bellman ford algorithm  For all cases, the complexity of this algorithm will be determined by the number of edge comparisons. if temporaryDist < dist[v] Edge relaxation differences depend on the graph and the sequence of looking in on edges in the graph. The algorithm may need to undergo all repetitions while updating edges, but in many cases, the result is obtained in the first few iterations, so no updates are required. dist[v] <- temporaryDist Worst-Case Time Complexity When you come across a negative cycle in the graph, you can have a worst-case scenario. As an example of a negative cycle, consider the following: In a complete graph with edges between every pair of vertices, and assuming you found the shortest path in the first few iterations or repetitions but still go on with edge relaxation, you would have to relax |E| * (|E| - 1) / 2 edges, (|V| - 1) number of times. The worst-case scenario in the case of a complete graph, the time complexity is as follows: O(|V|2) = O(E V). O(|V|) = O (V3) Average Case Time Complexity You can reduce the worst-case running time by stopping the algorithm when no changes are made to the path values. As a result, there will be fewer iterations. Another way to improve it is to ignore any vertex V with a distance value that has not changed since the last relaxation in subsequent iterations, reducing the number of edges that need to be relaxed and increasing the number of edges with correct values after each iteration. More information is available at the link at the bottom of this post. Relaxation occurs |V| - 1 time for every |E| the number of edges, so you multiply the two and get the average, which is the quadratic time complexity of O. (E V). Best Case Time Complexity If edge relaxation occurs from left to right in the above graph, the algorithm would only need to perform one relaxation iteration to find the shortest path, resulting in the time complexity of O(E) corresponding to the number of edges in the graph. The following is the space complexity of the bellman ford algorithm: The space complexity of the Bellman-Ford algorithm is O(V). Following that, in this Bellman-Ford algorithm tutorial, you will look at some use cases of the Bellman-Ford algorithm. Uses of Bellman-Ford Algorithm There are several real-world applications for the Bellman-Ford algorithm, including: Identifying negative weight cycles In a chemical reaction, calculate the smallest possible heat gain/loss. Identifying the most efficient currency conversion method. You will now peek at some applications of the Bellman-Ford algorithm in this tutorial. Applications of the Bellman-Ford Algorithm Following are the applications of the bellman ford algorithm: Examining a graph for the presence of negative weight cycles. Using negative weights, find the shortest path in a graph. Routing is a concept used in data networks. Last but not least, you will need to perform practical demonstrations of the Bellman-Ford algorithm in the C programming language.  Code Demonstration of Bellman-Ford Algorithm #include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> #include<limits.h> struct Edges {     // This structure is equal to an edge. Edge contains two endpoints. These edges are directed edges so they //contain source and destination and some weight. These 3 are elements in this structure     int src, dest, wt; }; // a structure to represent a graph struct Graph {     int Vertex, Edge; //Vertex is the number of vertices, and Edge is the number of edges     struct Edges* edge; // This structure contains another structure that we have already created. }; struct Graph* designGraph(int Vertex, int Edge) {     struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph)); //Allocating space to structure graph     graph->Vertex = Vertex; //assigning values to structure elements that taken form user.     graph->Edge = Edge;     graph->edge = (struct Edges*) malloc( graph->Edge * sizeof( struct Edges ) ); //Creating "Edge" type structures inside "Graph" structure, the number of edge type structures are equal to number of edges      return graph; } void Solution(int dist[], int n) { // This function prints the last solution     printf("\nVertex\tDistance from Source Vertex\n");     int i;     for (i = 0; i < n; ++i){ printf("%d \t\t %d\n", i, dist[i]); } } void BellmanFordalgorithm(struct Graph* graph, int src) {     int Vertex = graph->Vertex;     int Edge = graph->Edge;     int Distance[Vertex];     int i,j;     // This is the initial step that we know, and we initialize all distances to infinity except the source vertex. // We assign source distance as 0     for (i = 0; i < Vertex; i++)         Distance[i] = INT_MAX;     Distance[src] = 0;     //The shortest path of graph that contain Vertex vertices, never contain "Veretx-1" edges. So we do here "Vertex-1" relaxations     for (i = 1; i <= Vertex-1; i++)     {         for (j = 0; j < Edge; j++)         {             int u = graph->edge[j].src;              int v = graph->edge[j].dest;             int wt = graph->edge[j].wt;             if (Distance[u] + wt < Distance[v])                 Distance[v] = Distance[u] + wt;         }     }     //, up to now, the shortest path found. But BellmanFordalgorithm checks for negative edge cycles. In this step, we check for that     // shortest path if the graph doesn't contain any negative weight cycle in the graph.     // If we get a shorter path, then there is a negative edge cycle.     for (i = 0; i < Edge; i++)     {         int u = graph->edge[i].src;         int v = graph->edge[i].dest;         int wt = graph->edge[i].wt;         if (Distance[u] + wt < Distance[v])             printf("This graph contains negative edge cycle\n");     }      Solution(Distance, Vertex);     return; } int main() {     int V,E,S; //V = no.of Vertices, E = no.of Edges, S is source vertex printf("Enter number of vertices\n");     scanf("%d",&V); printf("Enter number of edges\n");     scanf("%d",&E); printf("Enter the source vertex number\n"); scanf("%d",&S);     struct Graph* graph = designGraph(V, E); //calling the function to allocate space to these many vertices and edges     int i;     for(i=0;i<E;i++){         printf("\nEnter edge %d properties Source, destination, weight respectively\n",i+1);         scanf("%d",&graph->edge[i].src);         scanf("%d",&graph->edge[i].dest);         scanf("%d",&graph->edge[i].wt);     }     BellmanFordalgorithm(graph, S); //passing created graph and source vertex to BellmanFord Algorithm function     return 0; } Output Now that you have reached the end of the Bellman-Ford tutorial, you will go over everything you’ve learned so far. Advance your career as a MEAN stack developer with the Post Graduate Program In Full Stack Web Development . Enroll now! Next Steps In this Bellman-Ford algorithm tutorial, you looked at what the algorithm is and how it works. You studied and comprehended the Bellman-Ford algorithm step-by-step, using the example as a guide. You also learned C programming language code and the output for calculating the distance from the source vertex in a weighted graph. And you saw the time complexity for applying the algorithm and the applications and uses that you can put to use in your daily lives. Assume you're looking for a more in-depth study that goes beyond Mobile and Software Development and covers today's most in-demand programming languages and skills. In that case, Simplilearn's software-development course is the right choice for you. Explore this globally recognized Bootcamp program. Rest assured that completing it will be the best decision you can make to enter and advance in the mobile and software development professions. Do you have any queries about this tutorial on Bellman-Ford Algorithm? Please leave them in the comments section at the bottom of this page if you do. Our experts will be happy to respond to your questions as earliest as possible!
Markdown
[![Simplilearn - Online Certification Training Course Provider](https://www.simplilearn.com/ice9/new_logo.svgz)](https://www.simplilearn.com/ "Simplilearn - Online Certification Training Course Provider") All Courses All Courses - [For Business](https://www.simplilearn.com/corporate-training "Simplilearn for Business") - [Resources](https://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm) - [Free Courses](https://www.simplilearn.com/skillup-free-online-courses "Free Courses") - [Free Resources](https://www.simplilearn.com/resources "Free Resources") - [More](https://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm) - [Reviews](https://www.simplilearn.com/reviews "Reviews") - [Become a Partner](https://www.simplilearn.com/reseller-partner-program-for-training-courses "Partners") - [Become an Instructor](https://www.simplilearn.com/become-our-trainer "Become an Instructor") [Login](https://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm "Login") Software Development [Data Science & Business Analytics](https://www.simplilearn.com/resources/data-science-business-analytics)[AI & Machine Learning](https://www.simplilearn.com/resources/artificial-intelligence-machine-learning)[Project Management](https://www.simplilearn.com/resources/project-management)[Cyber Security](https://www.simplilearn.com/resources/cyber-security)[Cloud Computing](https://www.simplilearn.com/resources/cloud-computing)[DevOps](https://www.simplilearn.com/resources/devops)[Business and Leadership](https://www.simplilearn.com/resources/business-and-leadership)[Quality Management](https://www.simplilearn.com/resources/quality-management)[Software Development](https://www.simplilearn.com/resources/software-development)[Agile and Scrum](https://www.simplilearn.com/resources/agile-and-scrum)[IT Service and Architecture](https://www.simplilearn.com/resources/it-service-management)[Digital Marketing](https://www.simplilearn.com/resources/digital-marketing)[Big Data](https://www.simplilearn.com/resources/big-data-and-analytics)[Career Fast-track](https://www.simplilearn.com/resources/career-fast-track)[Enterprise](https://www.simplilearn.com/resources/enterprise)[Other Segments](https://www.simplilearn.com/resources/other-segments) [Tutorials](https://www.simplilearn.com/resources/software-development/tutorials)[Articles](https://www.simplilearn.com/resources/software-development/articles)[Ebooks](https://www.simplilearn.com/resources/software-development/ebooks)[Free Practice Tests](https://www.simplilearn.com/resources/software-development/free-practice-tests)[On-demand Webinars](https://www.simplilearn.com/resources/software-development/on-demand-webinars) [Home](https://www.simplilearn.com/)[Resources](https://www.simplilearn.com/resources)[Software Development](https://www.simplilearn.com/resources/software-development)[Data Structure Tutorial for Beginners](https://www.simplilearn.com/tutorials/data-structure-tutorial)Bellman-Ford Algorithm: Pseudocode, Time Complexity and Examples Tutorial Playlist [Data Structure TutorialOverview](https://www.simplilearn.com/tutorials/data-structure-tutorial) [Arrays in Data Structures: A Guide With ExamplesLesson - 1](https://www.simplilearn.com/tutorials/data-structure-tutorial/arrays-in-data-structure) [All You Need to Know About Two-Dimensional ArraysLesson - 2](https://www.simplilearn.com/tutorials/data-structure-tutorial/two-dimensional-arrays) [All You Need to Know About a Linked List in a Data StructureLesson - 3](https://www.simplilearn.com/tutorials/data-structure-tutorial/linked-list-in-data-structure) [The Complete Guide to Implement a Singly Linked ListLesson - 4](https://www.simplilearn.com/tutorials/data-structure-tutorial/singly-linked-list) [The Ultimate Guide to Implement a Doubly Linked ListLesson - 5](https://www.simplilearn.com/tutorials/data-structure-tutorial/doubly-linked-list) [The Fundamentals for Understanding Circular Linked ListLesson - 6](https://www.simplilearn.com/tutorials/data-structure-tutorial/circular-linked-list) [The Ultimate Guide To Understand The Differences Between Stack And QueueLesson - 7](https://www.simplilearn.com/tutorials/data-structure-tutorial/stacks-and-queues) [Implementing Stacks in Data StructuresLesson - 8](https://www.simplilearn.com/tutorials/data-structure-tutorial/stacks-in-data-structures) [Your One-Stop Solution for Stack Implementation Using ArrayLesson - 9](https://www.simplilearn.com/tutorials/data-structure-tutorial/stack-implementation-using-array) [Your One-Stop Solution for Queue Implementation Using ArrayLesson - 10](https://www.simplilearn.com/tutorials/data-structure-tutorial/queue-implementation-using-array) [Your One-Stop Solution to Learn Depth-First Search(DFS) Algorithm From ScratchLesson - 11](https://www.simplilearn.com/tutorials/data-structure-tutorial/dfs-algorithm) [Your One-Stop Solution for Stack Implementation Using Linked-ListLesson - 12](https://www.simplilearn.com/tutorials/data-structure-tutorial/stack-implementation-using-linked-list) [The Definitive Guide to Understand Stack vs Heap Memory AllocationLesson - 13](https://www.simplilearn.com/tutorials/data-structure-tutorial/stacks-vs-heap) [All You Need to Know About Linear Search AlgorithmLesson - 14](https://www.simplilearn.com/tutorials/data-structure-tutorial/linear-search-algorithm) [All You Need to Know About Breadth-First Search AlgorithmLesson - 15](https://www.simplilearn.com/tutorials/data-structure-tutorial/bfs-algorithm) [A One-Stop Solution for Using Binary Search Trees in Data StructureLesson - 16](https://www.simplilearn.com/tutorials/data-structure-tutorial/binary-search-tree-in-data-structure) [The Best Tutorial to Understand Trees in Data StructureLesson - 17](https://www.simplilearn.com/tutorials/data-structure-tutorial/trees-in-data-structure) [A Complete Guide to Implement Binary Tree in Data StructureLesson - 18](https://www.simplilearn.com/tutorials/data-structure-tutorial/binary-tree-in-data-structures) [A Holistic Look at Using AVL Trees in Data StructuresLesson - 19](https://www.simplilearn.com/tutorials/data-structure-tutorial/avl-tree-in-data-structure) [All You Need to Know About Tree Traversal in Data StructureLesson - 20](https://www.simplilearn.com/tutorials/data-structure-tutorial/tree-traversal-in-data-structure) [What is An Algorithm? Definition, Working, and TypesLesson - 21](https://www.simplilearn.com/tutorials/data-structure-tutorial/what-is-an-algorithm) [The Best Guide You’ll Ever Need to Understand B-Tree in Data StructureLesson - 22](https://www.simplilearn.com/tutorials/data-structure-tutorial/b-tree-in-data-structure) [The Best Guide You'll Ever Need to Understand Spanning Tree in Data StructureLesson - 23](https://www.simplilearn.com/tutorials/data-structure-tutorial/spanning-tree-in-data-structure) [A One-Stop Solution Guide to Understand Data Structure and Algorithm ComplexityLesson - 24](https://www.simplilearn.com/tutorials/data-structure-tutorial/algorithm-complexity-in-data-structure) [Your One-Stop Solution to Understand Shell Sort AlgorithmLesson - 25](https://www.simplilearn.com/tutorials/data-structure-tutorial/shell-sort) [Your One-Stop Solution to Quick Sort AlgorithmLesson - 26](https://www.simplilearn.com/tutorials/data-structure-tutorial/quick-sort-algorithm) [What Is Selection Sort Algorithm In Data Structures?Lesson - 27](https://www.simplilearn.com/tutorials/data-structure-tutorial/selection-sort-algorithm) [Everything You Need to Know About Radix Sort AlgorithmLesson - 28](https://www.simplilearn.com/tutorials/data-structure-tutorial/radix-sort) [Everything You Need to Know About the Counting Sort AlgorithmLesson - 29](https://www.simplilearn.com/tutorials/data-structure-tutorial/counting-sort-algorithm) [Everything You Need to Know About the Merge Sort AlgorithmLesson - 30](https://www.simplilearn.com/tutorials/data-structure-tutorial/merge-sort-algorithm) [Insertion Sort Algorithm: One-Stop Solution That Will Help You Understand Insertion SortLesson - 31](https://www.simplilearn.com/tutorials/data-structure-tutorial/insertion-sort-algorithm) [Everything You Need to Know About the Bubble Sort AlgorithmLesson - 32](https://www.simplilearn.com/tutorials/data-structure-tutorial/bubble-sort-algorithm) [The Best Guide You’ll Ever Need to Understand Bucket Sort AlgorithmLesson - 33](https://www.simplilearn.com/tutorials/data-structure-tutorial/bucket-sort-algorithm) [Your One-Stop Solution to Understand Recursive Algorithm in ProgrammingLesson - 34](https://www.simplilearn.com/tutorials/data-structure-tutorial/recursive-algorithm) [The Definitive Guide to Understanding Greedy AlgorithmLesson - 35](https://www.simplilearn.com/tutorials/data-structure-tutorial/greedy-algorithm) [Your One-Stop Solution to Understand Backtracking AlgorithmLesson - 36](https://www.simplilearn.com/tutorials/data-structure-tutorial/backtracking-algorithm) [The Fundamentals of the Bellman-Ford AlgorithmLesson - 37](https://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm) [Your One-Stop Solution for Graphs in Data StructuresLesson - 38](https://www.simplilearn.com/tutorials/data-structure-tutorial/graphs-in-data-structure) [The Best Guide to Understand and Implement Solutions for Tower of Hanoi PuzzleLesson - 39](https://www.simplilearn.com/tutorials/data-structure-tutorial/tower-of-hanoi) [A Simplified and Complete Guide to Learn Space and Time ComplexityLesson - 40](https://www.simplilearn.com/tutorials/data-structure-tutorial/time-and-space-complexity) [All You Need to Know About the Knapsack Problem : Your Complete GuideLesson - 41](https://www.simplilearn.com/tutorials/data-structure-tutorial/knapsack-problem) [The Fibonacci Series: Mathematical and Programming InterpretationLesson - 42](https://www.simplilearn.com/tutorials/data-structure-tutorial/what-is-fibonacci-series-in-c) [The Holistic Look at Longest Common Subsequence ProblemLesson - 43](https://www.simplilearn.com/tutorials/data-structure-tutorial/longest-common-subsequence) [The Best Article to Understand What Is Dynamic ProgrammingLesson - 44](https://www.simplilearn.com/tutorials/data-structure-tutorial/what-is-dynamic-programming) [A Guide to Implement Longest Increasing Subsequence Using Dynamic ProgrammingLesson - 45](https://www.simplilearn.com/tutorials/data-structure-tutorial/longest-increasing-subsequence) [A Holistic Guide to Learn Stop Solution Using Dynamic ProgrammingLesson - 46](https://www.simplilearn.com/tutorials/data-structure-tutorial/subset-sum-problem) [One Stop Solution to All the Dynamic Programming ProblemsLesson - 47](https://www.simplilearn.com/tutorials/data-structures-tutorial/dynamic-programming-problems) [Understanding the Fundamentals of Binomial DistributionLesson - 48](https://www.simplilearn.com/tutorials/statistics-tutorial/binomial-distribution) [Here’s All You Need to Know About Minimum Spanning Tree in Data StructuresLesson - 49](https://www.simplilearn.com/tutorials/data-structure-tutorial/minimum-spanning-tree-algorithm-in-data-structure) [Understanding the Difference Between Array and Linked ListLesson - 50](https://www.simplilearn.com/tutorials/data-structure-tutorial/difference-between-array-and-linked-list-in-data-structure) [The Best Article Out There to Understand the B+ Tree in Data StructureLesson - 51](https://www.simplilearn.com/tutorials/data-structure-tutorial/b-plus-tree-in-data-structure) [A Comprehensive Look at Queue in Data StructureLesson - 52](https://www.simplilearn.com/tutorials/data-structure-tutorial/queue-in-data-structure) [Your One-Stop Solution to Understand Coin Change ProblemLesson - 53](https://www.simplilearn.com/tutorials/data-structure-tutorial/coin-change-problem-with-dynamic-programming) [The Best Way to Understand the Matrix Chain Multiplication ProblemLesson - 54](https://www.simplilearn.com/tutorials/data-structure-tutorial/matrix-chain-multiplication) [Your One-Stop Solution to Learn Floyd-Warshall Algorithm for Using Dynamic ProgrammingLesson - 55](https://www.simplilearn.com/tutorials/data-structures-tutorial/floyd-warshall-algorithm-for-using-dynamic-programming) [The Best Tutorial You'll Ever Need for Queue Implementation Using Linked ListLesson - 56](https://www.simplilearn.com/tutorials/data-structure-tutorial/queue-using-linked-list) [All You Need to Know About How to Create a React JS Portfolio ProjectLesson - 57](https://www.simplilearn.com/tutorials/reactjs-tutorial/how-to-create-a-react-js-portfolio-project) [The Best Guide to Learn How to Make a Wireframe: What is a Wireframe?Lesson - 58](https://www.simplilearn.com/tutorials/programming-tutorial/what-is-a-wireframe-and-how-to-make-one) [The Best DSA Projects for Your ResumeLesson - 59](https://www.simplilearn.com/tutorials/data-structure-tutorial/best-dsa-projects) [Top 5 Best Coding Books You Must ReadLesson - 60](https://www.simplilearn.com/tutorials/programming-tutorial/best-coding-books-you-must-read) [The Working and Implementation of Physical Layer in the OSI ModelLesson - 61](https://www.simplilearn.com/tutorials/cyber-security-tutorial/physical-layer-in-the-osi-model) [How to Create an Instagram Clone Using React?Lesson - 62](https://www.simplilearn.com/tutorials/reactjs-tutorial/how-to-create-an-instagram-clone-using-react) [ReactJS Vs VueJSLesson - 63](https://www.simplilearn.com/tutorials/vuejs-tutorial/vue-js-vs-react) # Bellman-Ford Algorithm: Pseudocode, Time Complexity and Examples Lesson 37 of 63 [By Soni Upadhyay](https://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm)Last updated on Jan 26, 202575355 ![The Fundamentals of the Bellman-Ford Algorithm](https://i.ytimg.com/vi/ILeK8R0o0mQ/hqdefault.jpg) [Previous](https://www.simplilearn.com/tutorials/data-structure-tutorial/backtracking-algorithm)[Next](https://www.simplilearn.com/tutorials/data-structure-tutorial/graphs-in-data-structure) - [Tutorial Playlist](https://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm) [Data Structure TutorialOverview](https://www.simplilearn.com/tutorials/data-structure-tutorial) [Arrays in Data Structures: A Guide With ExamplesLesson - 1](https://www.simplilearn.com/tutorials/data-structure-tutorial/arrays-in-data-structure) [All You Need to Know About Two-Dimensional ArraysLesson - 2](https://www.simplilearn.com/tutorials/data-structure-tutorial/two-dimensional-arrays) [All You Need to Know About a Linked List in a Data StructureLesson - 3](https://www.simplilearn.com/tutorials/data-structure-tutorial/linked-list-in-data-structure) [The Complete Guide to Implement a Singly Linked ListLesson - 4](https://www.simplilearn.com/tutorials/data-structure-tutorial/singly-linked-list) [The Ultimate Guide to Implement a Doubly Linked ListLesson - 5](https://www.simplilearn.com/tutorials/data-structure-tutorial/doubly-linked-list) [The Fundamentals for Understanding Circular Linked ListLesson - 6](https://www.simplilearn.com/tutorials/data-structure-tutorial/circular-linked-list) [The Ultimate Guide To Understand The Differences Between Stack And QueueLesson - 7](https://www.simplilearn.com/tutorials/data-structure-tutorial/stacks-and-queues) [Implementing Stacks in Data StructuresLesson - 8](https://www.simplilearn.com/tutorials/data-structure-tutorial/stacks-in-data-structures) [Your One-Stop Solution for Stack Implementation Using ArrayLesson - 9](https://www.simplilearn.com/tutorials/data-structure-tutorial/stack-implementation-using-array) [Your One-Stop Solution for Queue Implementation Using ArrayLesson - 10](https://www.simplilearn.com/tutorials/data-structure-tutorial/queue-implementation-using-array) [Your One-Stop Solution to Learn Depth-First Search(DFS) Algorithm From ScratchLesson - 11](https://www.simplilearn.com/tutorials/data-structure-tutorial/dfs-algorithm) [Your One-Stop Solution for Stack Implementation Using Linked-ListLesson - 12](https://www.simplilearn.com/tutorials/data-structure-tutorial/stack-implementation-using-linked-list) [The Definitive Guide to Understand Stack vs Heap Memory AllocationLesson - 13](https://www.simplilearn.com/tutorials/data-structure-tutorial/stacks-vs-heap) [All You Need to Know About Linear Search AlgorithmLesson - 14](https://www.simplilearn.com/tutorials/data-structure-tutorial/linear-search-algorithm) [All You Need to Know About Breadth-First Search AlgorithmLesson - 15](https://www.simplilearn.com/tutorials/data-structure-tutorial/bfs-algorithm) [A One-Stop Solution for Using Binary Search Trees in Data StructureLesson - 16](https://www.simplilearn.com/tutorials/data-structure-tutorial/binary-search-tree-in-data-structure) [The Best Tutorial to Understand Trees in Data StructureLesson - 17](https://www.simplilearn.com/tutorials/data-structure-tutorial/trees-in-data-structure) [A Complete Guide to Implement Binary Tree in Data StructureLesson - 18](https://www.simplilearn.com/tutorials/data-structure-tutorial/binary-tree-in-data-structures) [A Holistic Look at Using AVL Trees in Data StructuresLesson - 19](https://www.simplilearn.com/tutorials/data-structure-tutorial/avl-tree-in-data-structure) [All You Need to Know About Tree Traversal in Data StructureLesson - 20](https://www.simplilearn.com/tutorials/data-structure-tutorial/tree-traversal-in-data-structure) [What is An Algorithm? Definition, Working, and TypesLesson - 21](https://www.simplilearn.com/tutorials/data-structure-tutorial/what-is-an-algorithm) [The Best Guide You’ll Ever Need to Understand B-Tree in Data StructureLesson - 22](https://www.simplilearn.com/tutorials/data-structure-tutorial/b-tree-in-data-structure) [The Best Guide You'll Ever Need to Understand Spanning Tree in Data StructureLesson - 23](https://www.simplilearn.com/tutorials/data-structure-tutorial/spanning-tree-in-data-structure) [A One-Stop Solution Guide to Understand Data Structure and Algorithm ComplexityLesson - 24](https://www.simplilearn.com/tutorials/data-structure-tutorial/algorithm-complexity-in-data-structure) [Your One-Stop Solution to Understand Shell Sort AlgorithmLesson - 25](https://www.simplilearn.com/tutorials/data-structure-tutorial/shell-sort) [Your One-Stop Solution to Quick Sort AlgorithmLesson - 26](https://www.simplilearn.com/tutorials/data-structure-tutorial/quick-sort-algorithm) [What Is Selection Sort Algorithm In Data Structures?Lesson - 27](https://www.simplilearn.com/tutorials/data-structure-tutorial/selection-sort-algorithm) [Everything You Need to Know About Radix Sort AlgorithmLesson - 28](https://www.simplilearn.com/tutorials/data-structure-tutorial/radix-sort) [Everything You Need to Know About the Counting Sort AlgorithmLesson - 29](https://www.simplilearn.com/tutorials/data-structure-tutorial/counting-sort-algorithm) [Everything You Need to Know About the Merge Sort AlgorithmLesson - 30](https://www.simplilearn.com/tutorials/data-structure-tutorial/merge-sort-algorithm) [Insertion Sort Algorithm: One-Stop Solution That Will Help You Understand Insertion SortLesson - 31](https://www.simplilearn.com/tutorials/data-structure-tutorial/insertion-sort-algorithm) [Everything You Need to Know About the Bubble Sort AlgorithmLesson - 32](https://www.simplilearn.com/tutorials/data-structure-tutorial/bubble-sort-algorithm) [The Best Guide You’ll Ever Need to Understand Bucket Sort AlgorithmLesson - 33](https://www.simplilearn.com/tutorials/data-structure-tutorial/bucket-sort-algorithm) [Your One-Stop Solution to Understand Recursive Algorithm in ProgrammingLesson - 34](https://www.simplilearn.com/tutorials/data-structure-tutorial/recursive-algorithm) [The Definitive Guide to Understanding Greedy AlgorithmLesson - 35](https://www.simplilearn.com/tutorials/data-structure-tutorial/greedy-algorithm) [Your One-Stop Solution to Understand Backtracking AlgorithmLesson - 36](https://www.simplilearn.com/tutorials/data-structure-tutorial/backtracking-algorithm) [The Fundamentals of the Bellman-Ford AlgorithmLesson - 37](https://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm) [Your One-Stop Solution for Graphs in Data StructuresLesson - 38](https://www.simplilearn.com/tutorials/data-structure-tutorial/graphs-in-data-structure) [The Best Guide to Understand and Implement Solutions for Tower of Hanoi PuzzleLesson - 39](https://www.simplilearn.com/tutorials/data-structure-tutorial/tower-of-hanoi) [A Simplified and Complete Guide to Learn Space and Time ComplexityLesson - 40](https://www.simplilearn.com/tutorials/data-structure-tutorial/time-and-space-complexity) [All You Need to Know About the Knapsack Problem : Your Complete GuideLesson - 41](https://www.simplilearn.com/tutorials/data-structure-tutorial/knapsack-problem) [The Fibonacci Series: Mathematical and Programming InterpretationLesson - 42](https://www.simplilearn.com/tutorials/data-structure-tutorial/what-is-fibonacci-series-in-c) [The Holistic Look at Longest Common Subsequence ProblemLesson - 43](https://www.simplilearn.com/tutorials/data-structure-tutorial/longest-common-subsequence) [The Best Article to Understand What Is Dynamic ProgrammingLesson - 44](https://www.simplilearn.com/tutorials/data-structure-tutorial/what-is-dynamic-programming) [A Guide to Implement Longest Increasing Subsequence Using Dynamic ProgrammingLesson - 45](https://www.simplilearn.com/tutorials/data-structure-tutorial/longest-increasing-subsequence) [A Holistic Guide to Learn Stop Solution Using Dynamic ProgrammingLesson - 46](https://www.simplilearn.com/tutorials/data-structure-tutorial/subset-sum-problem) [One Stop Solution to All the Dynamic Programming ProblemsLesson - 47](https://www.simplilearn.com/tutorials/data-structures-tutorial/dynamic-programming-problems) [Understanding the Fundamentals of Binomial DistributionLesson - 48](https://www.simplilearn.com/tutorials/statistics-tutorial/binomial-distribution) [Here’s All You Need to Know About Minimum Spanning Tree in Data StructuresLesson - 49](https://www.simplilearn.com/tutorials/data-structure-tutorial/minimum-spanning-tree-algorithm-in-data-structure) [Understanding the Difference Between Array and Linked ListLesson - 50](https://www.simplilearn.com/tutorials/data-structure-tutorial/difference-between-array-and-linked-list-in-data-structure) [The Best Article Out There to Understand the B+ Tree in Data StructureLesson - 51](https://www.simplilearn.com/tutorials/data-structure-tutorial/b-plus-tree-in-data-structure) [A Comprehensive Look at Queue in Data StructureLesson - 52](https://www.simplilearn.com/tutorials/data-structure-tutorial/queue-in-data-structure) [Your One-Stop Solution to Understand Coin Change ProblemLesson - 53](https://www.simplilearn.com/tutorials/data-structure-tutorial/coin-change-problem-with-dynamic-programming) [The Best Way to Understand the Matrix Chain Multiplication ProblemLesson - 54](https://www.simplilearn.com/tutorials/data-structure-tutorial/matrix-chain-multiplication) [Your One-Stop Solution to Learn Floyd-Warshall Algorithm for Using Dynamic ProgrammingLesson - 55](https://www.simplilearn.com/tutorials/data-structures-tutorial/floyd-warshall-algorithm-for-using-dynamic-programming) [The Best Tutorial You'll Ever Need for Queue Implementation Using Linked ListLesson - 56](https://www.simplilearn.com/tutorials/data-structure-tutorial/queue-using-linked-list) [All You Need to Know About How to Create a React JS Portfolio ProjectLesson - 57](https://www.simplilearn.com/tutorials/reactjs-tutorial/how-to-create-a-react-js-portfolio-project) [The Best Guide to Learn How to Make a Wireframe: What is a Wireframe?Lesson - 58](https://www.simplilearn.com/tutorials/programming-tutorial/what-is-a-wireframe-and-how-to-make-one) [The Best DSA Projects for Your ResumeLesson - 59](https://www.simplilearn.com/tutorials/data-structure-tutorial/best-dsa-projects) [Top 5 Best Coding Books You Must ReadLesson - 60](https://www.simplilearn.com/tutorials/programming-tutorial/best-coding-books-you-must-read) [The Working and Implementation of Physical Layer in the OSI ModelLesson - 61](https://www.simplilearn.com/tutorials/cyber-security-tutorial/physical-layer-in-the-osi-model) [How to Create an Instagram Clone Using React?Lesson - 62](https://www.simplilearn.com/tutorials/reactjs-tutorial/how-to-create-an-instagram-clone-using-react) [ReactJS Vs VueJSLesson - 63](https://www.simplilearn.com/tutorials/vuejs-tutorial/vue-js-vs-react) ## Table of Contents View More The Bellman-Ford algorithm emulates the shortest paths from a single source vertex to all other vertices in a weighted digraph. It is slower than Dijkstra's algorithm for the same problem but more versatile because it can handle graphs with some edge weights that are negative numbers. Alfonso Shimbel proposed the algorithm in 1955, but it is now named after Richard Bellman and Lester Ford Jr., who brought it out in 1958 and 1956. In 1959, Edward F. Moore published a variation of the [algorithm](https://www.simplilearn.com/data-structures-and-algorithms-article "algorithm"), sometimes referred to as the Bellman-Ford–Moore algorithm. Want a Top Software Development Job? Start Here\!AI-Powered Full Stack Developer Program[Explore Program](https://www.simplilearn.com/full-stack-developer-course-mern-certification-training?source=GhPreviewCTABanner) ![Want a Top Software Development Job? Start Here\!](https://www.simplilearn.com/ice9/assets/form_opacity.png) ## What Is the Bellman-Ford Algorithm? Dynamic Programming is used in the Bellman-Ford algorithm. It begins with a starting vertex and calculates the distances between other vertices that a single edge can reach. It then searches for a path with two edges, and so on. The Bellman-Ford algorithm uses the bottom-up approach. ![what-is-bellman-ford-algorithm.](https://www.simplilearn.com/ice9/assets/form_opacity.png) Based on the "Principle of Relaxation," more accurate values gradually recovered an approximation to the proper distance until finally reaching the optimum solution. Negative weight edges can generate negative weight cycles, which reduce the total path distance by returning to the same point. ### Why Should You Be Cautious With Negative Weights? When attempting to find the shortest path, negative weight cycles may produce an incorrect result. Shortest path algorithms, such as Dijkstra's Algorithm that cannot detect such a cycle, may produce incorrect results because they may go through a negative weight cycle, reducing the path length. After learning about the Bellman-Ford algorithm, you will look at how it works in this tutorial. Want a Top Software Development Job? Start Here\!AI-Powered Full Stack Developer Program[Explore Program](https://www.simplilearn.com/full-stack-developer-course-mern-certification-training?source=GhPreviewCTABanner) ![Want a Top Software Development Job? Start Here\!](https://www.simplilearn.com/ice9/assets/form_opacity.png) ## How Does the Bellman-Ford Algorithm Work? The Bellman-Ford algorithm works by grossly underestimating the length of the path from the starting vertex to all other vertices. The algorithm then iteratively relaxes those estimates by discovering new ways that are shorter than the previously overestimated paths. You can ensure that the result is optimized by repeating this process for all vertices. Step 1: Make a list of all the graph's edges. This is simple if an adjacency list represents the graph. Step 2: "V - 1" is used to calculate the number of iterations. Because the shortest distance to an edge can be adjusted V - 1 time at most, the number of iterations will increase the same number of vertices. Step 3: Begin with an arbitrary vertex and a minimum distance of zero. Because you are exaggerating the actual distances, all other nodes should be assigned infinity. For each edge u-v, relax the path lengths for the vertices: If distance\[v\] is greater than distance\[u\] + edge weight uv, then distance\[v\] = distance\[u\] + edge weight uv Step 4:If the new distance is less than the previous one, update the distance for each Edge in each iteration. The distance to each node is the total distance from the starting node to this specific node. Step 5: To ensure that all possible paths are considered, you must consider alliterations. You will end up with the shortest distance if you do this. Moving ahead with this tutorial on the Bellman-Ford algorithm, you will now learn the pseudocode for this algorithm. Want a Top Software Development Job? Start Here\!AI-Powered Full Stack Developer Program[Explore Program](https://www.simplilearn.com/full-stack-developer-course-mern-certification-training?source=GhPreviewCTABanner) ![Want a Top Software Development Job? Start Here\!](https://www.simplilearn.com/ice9/assets/form_opacity.png) ## Pseudocode of the Bellman-Ford Algorithm Every Vertex's path distance must be maintained. That can be stored in a V-dimensional array, where V is the number of vertices. Not only do you need to know the length of the shortest path, but you also need to be able to find it. To accomplish this, you must map each Vertex to the Vertex that most recently updated its path length. When the algorithm is finished, you can find the path from the destination vertex to the source. | | |---| | function bellmanFordAlgorithm(G, s) //G is the graph and s is the source vertex for each vertex V in G dist\[V\] \<- infinite // dist is distance prev\[V\] \<- NULL // prev is previous dist\[s\] \<- 0 for each vertex V in G for each edge (u,v) in G temporaryDist \<- dist\[u\] + edgeweight(u, v) if temporaryDist \< dist\[v\] dist\[v\] \<- temporaryDist prev\[v\] \<- u for each edge (U,V) in G If dist\[U\] + edgeweight(U, V) \< dist\[V} Error: Negative Cycle Exists return dist\[\], previ\[\] | As you progress through this tutorial, you will see an example of the Bellman-Ford algorithm for a better learning experience. ## An Example of Bellman-Ford Algorithm Consider the weighted graph below. ![Example-of-bellman-ford-algorithm.](https://www.simplilearn.com/ice9/assets/form_opacity.png) - Choose path value 0 for the source vertex and infinity for all other vertices. ![Example-of-bellman-ford-algorithm1.](https://www.simplilearn.com/ice9/assets/form_opacity.png) - If the new calculated path length is less than the previous path length, go to the source vertex's neighboring Edge and relax the path length of the adjacent Vertex. ![Example-of-bellman-ford-algorithm2.](https://www.simplilearn.com/ice9/assets/form_opacity.png) Want a Top Software Development Job? Start Here\!AI-Powered Full Stack Developer Program[Explore Program](https://www.simplilearn.com/full-stack-developer-course-mern-certification-training?source=GhPreviewCTABanner) ![Want a Top Software Development Job? Start Here\!](https://www.simplilearn.com/ice9/assets/form_opacity.png) - This procedure must be repeated V-1 times, where V is the number of vertices in total. This happened because, in the worst-case scenario, any vertex's path length can be changed N times to an even shorter path length. ![Example-of-bellman-ford-algorithm3.](https://www.simplilearn.com/ice9/assets/form_opacity.png) ![Example-of-bellman-ford-algorithm3](https://www.simplilearn.com/ice9/assets/form_opacity.png) - As a result, after V-1 iterations, you find your new path lengths and can determine in case the graph has a negative cycle or not. ![Example-of-bellman-ford-algorithm5](https://www.simplilearn.com/ice9/assets/form_opacity.png) You will now look at the time and space complexity of the Bellman-Ford algorithm after you have a better understanding of it. ## The Complexity of Bellman-Ford Algorithm Following is the time complexity of the bellman ford algorithm For all cases, the complexity of this algorithm will be determined by the number of edge comparisons. | | |---| | if temporaryDist \< dist\[v\] | Edge relaxation differences depend on the graph and the sequence of looking in on edges in the graph. The algorithm may need to undergo all repetitions while updating edges, but in many cases, the result is obtained in the first few iterations, so no updates are required. | | |---| | dist\[v\] \<- temporaryDist | - ### Worst-Case Time Complexity When you come across a negative cycle in the graph, you can have a worst-case scenario. As an example of a negative cycle, consider the following: ![worst-case-bellman-ford-algorithm.](https://www.simplilearn.com/ice9/assets/form_opacity.png) In a complete graph with edges between every pair of vertices, and assuming you found the shortest path in the first few iterations or repetitions but still go on with edge relaxation, you would have to relax \|E\| \* (\|E\| - 1) / 2 edges, (\|V\| - 1) number of times. The worst-case scenario in the case of a complete graph, the time complexity is as follows: O(\|V\|2) = O(E V). O(\|V\|) = O (V3) - ### Average Case Time Complexity You can reduce the worst-case running time by stopping the algorithm when no changes are made to the path values. As a result, there will be fewer iterations. Another way to improve it is to ignore any vertex V with a distance value that has not changed since the last relaxation in subsequent iterations, reducing the number of edges that need to be relaxed and increasing the number of edges with correct values after each iteration. More information is available at the link at the bottom of this post. Relaxation occurs \|V\| - 1 time for every \|E\| the number of edges, so you multiply the two and get the average, which is the quadratic time complexity of O. (E V). Automation Test Engineer Master's ProgramTo learn about the automation of web applications[Explore Course](https://www.simplilearn.com/automation-testing-masters-program-certification-training-course?source=GhPreviewCTAText) ![Automation Test Engineer Master's Program](https://www.simplilearn.com/ice9/assets/form_opacity.png) - ### Best Case Time Complexity ![best-case-time-complexity-in-bellman-ford-algorithm](https://www.simplilearn.com/ice9/assets/form_opacity.png) If edge relaxation occurs from left to right in the above graph, the algorithm would only need to perform one relaxation iteration to find the shortest path, resulting in the time complexity of O(E) corresponding to the number of edges in the graph. The following is the space complexity of the bellman ford algorithm: The space complexity of the Bellman-Ford algorithm is O(V). Following that, in this Bellman-Ford algorithm tutorial, you will look at some use cases of the Bellman-Ford algorithm. ## Uses of Bellman-Ford Algorithm There are several real-world applications for the Bellman-Ford algorithm, including: - Identifying negative weight cycles - In a chemical reaction, calculate the smallest possible heat gain/loss. - Identifying the most efficient currency conversion method. You will now peek at some applications of the Bellman-Ford algorithm in this tutorial. ## Applications of the Bellman-Ford Algorithm Following are the applications of the bellman ford algorithm: - Examining a graph for the presence of negative weight cycles. - Using negative weights, find the shortest path in a graph. - Routing is a concept used in data networks. Last but not least, you will need to perform practical demonstrations of the Bellman-Ford algorithm in the [C programming language.](https://www.simplilearn.com/c-programming-article "C programming language.") ## Code Demonstration of Bellman-Ford Algorithm | | |---| | \#include\<stdio.h\> \#include\<stdlib.h\> \#include\<conio.h\> \#include\<string.h\> \#include\<limits.h\> struct Edges { // This structure is equal to an edge. Edge contains two endpoints. These edges are directed edges so they //contain source and destination and some weight. These 3 are elements in this structure int src, dest, wt; }; // a structure to represent a graph struct Graph { int Vertex, Edge; //Vertex is the number of vertices, and Edge is the number of edges struct Edges\* edge; // This structure contains another structure that we have already created. }; struct Graph\* designGraph(int Vertex, int Edge) { struct Graph\* graph = (struct Graph\*) malloc( sizeof(struct Graph)); //Allocating space to structure graph graph-\>Vertex = Vertex; //assigning values to structure elements that taken form user. graph-\>Edge = Edge; graph-\>edge = (struct Edges\*) malloc( graph-\>Edge \* sizeof( struct Edges ) ); //Creating "Edge" type structures inside "Graph" structure, the number of edge type structures are equal to number of edges return graph; } void Solution(int dist\[\], int n) { // This function prints the last solution printf("\\nVertex\\tDistance from Source Vertex\\n"); int i; for (i = 0; i \< n; ++i){ printf("%d \\t\\t %d\\n", i, dist\[i\]); } } void BellmanFordalgorithm(struct Graph\* graph, int src) { int Vertex = graph-\>Vertex; int Edge = graph-\>Edge; int Distance\[Vertex\]; int i,j; // This is the initial step that we know, and we initialize all distances to infinity except the source vertex. // We assign source distance as 0 for (i = 0; i \< Vertex; i++) Distance\[i\] = INT\_MAX; Distance\[src\] = 0; //The shortest path of graph that contain Vertex vertices, never contain "Veretx-1" edges. So we do here "Vertex-1" relaxations for (i = 1; i \<= Vertex-1; i++) { for (j = 0; j \< Edge; j++) { int u = graph-\>edge\[j\].src; int v = graph-\>edge\[j\].dest; int wt = graph-\>edge\[j\].wt; if (Distance\[u\] + wt \< Distance\[v\]) Distance\[v\] = Distance\[u\] + wt; } } //, up to now, the shortest path found. But BellmanFordalgorithm checks for negative edge cycles. In this step, we check for that // shortest path if the graph doesn't contain any negative weight cycle in the graph. // If we get a shorter path, then there is a negative edge cycle. for (i = 0; i \< Edge; i++) { int u = graph-\>edge\[i\].src; int v = graph-\>edge\[i\].dest; int wt = graph-\>edge\[i\].wt; if (Distance\[u\] + wt \< Distance\[v\]) printf("This graph contains negative edge cycle\\n"); } Solution(Distance, Vertex); return; } int main() { int V,E,S; //V = no.of Vertices, E = no.of Edges, S is source vertex printf("Enter number of vertices\\n"); scanf("%d",\&V); printf("Enter number of edges\\n"); scanf("%d",\&E); printf("Enter the source vertex number\\n"); scanf("%d",\&S); struct Graph\* graph = designGraph(V, E); //calling the function to allocate space to these many vertices and edges int i; for(i=0;i\<E;i++){ printf("\\nEnter edge %d properties Source, destination, weight respectively\\n",i+1); scanf("%d",\&graph-\>edge\[i\].src); scanf("%d",\&graph-\>edge\[i\].dest); scanf("%d",\&graph-\>edge\[i\].wt); } BellmanFordalgorithm(graph, S); //passing created graph and source vertex to BellmanFord Algorithm function return 0; } | ### Output ![bellman-ford-algorithm-code-output](https://www.simplilearn.com/ice9/assets/form_opacity.png) Now that you have reached the end of the Bellman-Ford tutorial, you will go over everything you’ve learned so far. > Advance your career as a MEAN stack developer with the [Post Graduate Program In Full Stack Web Development](https://www.simplilearn.com/certifications/full-stack-courses?source=GhPreviewCoursepages "Post Graduate Program In Full Stack Web Development"). Enroll now\! Want a Top Software Development Job? Start Here\!AI-Powered Full Stack Developer Program[Explore Program](https://www.simplilearn.com/full-stack-developer-course-mern-certification-training?source=GhPreviewCTABanner) ![Want a Top Software Development Job? Start Here\!](https://www.simplilearn.com/ice9/assets/form_opacity.png) ## Next Steps In this Bellman-Ford algorithm tutorial, you looked at what the algorithm is and how it works. You studied and comprehended the Bellman-Ford algorithm step-by-step, using the example as a guide. You also learned C programming language code and the output for calculating the distance from the source vertex in a weighted graph. And you saw the time complexity for applying the algorithm and the applications and uses that you can put to use in your daily lives. Assume you're looking for a more in-depth study that goes beyond Mobile and [Software Development](https://www.simplilearn.com/what-is-a-software-developer-article "Software Development") and covers today's most in-demand [programming languages](https://www.simplilearn.com/evolution-of-programming-languages-article "programming languages") and skills. In that case, Simplilearn's [software-development](https://www.simplilearn.com/mobile-and-software-development "software-development") course is the right choice for you. Explore this globally recognized Bootcamp program. Rest assured that completing it will be the best decision you can make to enter and advance in the mobile and software development professions. Do you have any queries about this tutorial on Bellman-Ford Algorithm? Please leave them in the comments section at the bottom of this page if you do. Our experts will be happy to respond to your questions as earliest as possible\! ## About the Author ![Soni Upadhyay](https://www.simplilearn.com/ice9/assets/form_opacity.png)[Soni Upadhyay](https://www.simplilearn.com/tutorials/data-structure-tutorial/bellman-ford-algorithm) Soni Upadhyay is with Simplilearn's Research Analysis Team. She's a Computer Science and Engineering graduate. Programming languages are her area of expertise. She has a brilliant knowledge of C, C++, and Java Programming languages View More ## Recommended Programs [![AI-Powered Full Stack Developer Program](https://www.simplilearn.com/ice9/assets/form_opacity.png) AI-Powered Full Stack Developer Program 1367 Learners Lifetime Access\*](https://www.simplilearn.com/full-stack-developer-course-mern-certification-training/) [![Full Stack Java Developer Masters Program](https://www.simplilearn.com/ice9/assets/form_opacity.png) Full Stack Java Developer Masters Program 1028 Learners Lifetime Access\*](https://www.simplilearn.com/java-full-stack-developer-certification) \*Lifetime access to high-quality, self-paced e-learning content. [Explore Category](https://www.simplilearn.com/courses/software-development) ## Recommended Resources - [![Implementing Stacks in Data Structures](https://www.simplilearn.com/ice9/assets/form_opacity.png)Implementing Stacks in Data StructuresTutorial](https://www.simplilearn.com/tutorials/data-structure-tutorial/stacks-in-data-structures) - [![Top AI Jobs & How to Land Them in 2026](https://www.simplilearn.com/ice9/assets/form_opacity.png)Top AI Jobs & How to Land Them in 2026Ebook](https://www.simplilearn.com/top-ai-job-and-how-to-land-them-pdf) - [![Average Full Stack Developer Salary](https://www.simplilearn.com/ice9/assets/form_opacity.png)Average Full Stack Developer SalaryArticle](https://www.simplilearn.com/average-full-stack-developer-salary-article) - [![What is Power BI?: Architecture, and Features Explained](https://www.simplilearn.com/ice9/assets/form_opacity.png)What is Power BI?: Architecture, and Features ExplainedTutorial](https://www.simplilearn.com/tutorials/power-bi-tutorial/what-is-power-bi) - [![The Perfect Guide for All You Need to Learn About MEAN Stack](https://www.simplilearn.com/ice9/assets/form_opacity.png)The Perfect Guide for All You Need to Learn About MEAN StackTutorial](https://www.simplilearn.com/tutorials/express-js-tutorial/learn-mean-stack-a-perfect-guide) - [![GenAI in the Fast Lane - A Guide to Turbocharge Your Organization’s Capability](https://www.simplilearn.com/ice9/assets/form_opacity.png)GenAI in the Fast Lane - A Guide to Turbocharge Your Organization’s CapabilityEbook](https://www.simplilearn.com/guide-to-turbocharge-your-team-gen-ai-capabilities-pdf) prevNext © 2009 -2026- Simplilearn Solutions. Follow us\! [Refer and Earn](https://www.simplilearn.com/refer-and-earn "Refer and Earn") Company [About us](https://www.simplilearn.com/about-us "About us")[Careers](https://www.simplilearn.com/careers "Careers") [Newsroom](https://www.simplilearn.com/partners/sl/newsroom "Newsroom") [Alumni speak](https://www.simplilearn.com/reviews "Alumni speak") [Grievance redressal](https://www.simplilearn.com/grievance-redressal "Grievance redressal")[Contact us](https://www.simplilearn.com/contact-us "Contact us") Work with us [Become an instructor](https://www.simplilearn.com/become-our-trainer "Become an instructor")[Blog as guest](https://www.simplilearn.com/guest-blogging "Blog as guest") Discover [Free Courses](https://www.simplilearn.com/skillup-free-online-courses "Free Courses")[Skillup Sitemap](https://www.simplilearn.com/skillup-sitemap "Skillup Sitemap")[Resources](https://www.simplilearn.com/resources "Resources")[RSS feed](https://www.simplilearn.com/feed "RSS feed")[SimpliMentor GPT](https://chatgpt.com/g/g-67a4945c34108191b5f4bef996e630a0-simplimentor "SimpliMentor GPT") For Businesses [Corporate training](https://www.simplilearn.com/corporate-training "Corporate training")[Simplilearn Learning Hub+](https://www.simplilearn.com/corporate-training/learning-hub-plus "Simplilearn Learning Hub+")[Guaranteed-to-run Classes](https://www.simplilearn.com/corporate-training/guaranteed-to-run-classes "Guaranteed-to-run Classes")[Corporate resources](https://www.simplilearn.com/resources/enterprise "corporate-resources")[Partners](https://www.simplilearn.com/corporate-training/reseller-partner-program-for-training-courses "Partners") Learn On the Go\! [Get the Android App](https://play.google.com/store/apps/details?id=com.mobile.simplilearn "Get the Android App")[Get the iOS App](https://apps.apple.com/app/simplilearn/id963042747?ls=1 "Get the iOS App") Trending Post Graduate Programs [Product Management Certification Course](https://www.simplilearn.com/product-management-certification-training-course "Product Management Certification Course") \| [Product Management Training Course](https://www.simplilearn.com/product-management-training-course-online "Product Management Training Course") \| [Cloud Computing and DevOps Course](https://www.simplilearn.com/ai-cloud-computing-and-devops-course "Cloud Computing and DevOps Course") Trending Master Programs [PMP Plus Certification Training Course](https://www.simplilearn.com/pmp-plus-bundle-masters-program "PMP Plus Certification Training Course") \| [Data Science Certifiation Course](https://www.simplilearn.com/data-science-course "Data Science Certifiation Course") \| [Data Analyst Course](https://www.simplilearn.com/data-analyst-certification-course "Data Analyst Course") \| [Cloud Architect Certification Training Course](https://www.simplilearn.com/cloud-solutions-architect-masters-program-training "Cloud Architect Certification Training Course") \| [DevOps Engineer Certification Training Course](https://www.simplilearn.com/devops-engineer-masters-program-certification-training "DevOps Engineer Certification Training Course") \| [Cyber Security Expert Course](https://www.simplilearn.com/cyber-security-expert-master-program-training-course "Cyber Security Expert Course") \| [Business Analyst Course](https://www.simplilearn.com/business-analyst-certification-training-course "Business Analyst Course") \| [AI-Powered Automation Testing Course](https://www.simplilearn.com/automation-testing-masters-program-certification-training-course "AI-Powered Automation Testing Course") \| [Full Stack Java Developer Course](https://www.simplilearn.com/java-full-stack-developer-certification "Full Stack Java Developer Course") \| [AWS Cloud Architect Course](https://www.simplilearn.com/aws-cloud-architect-certification-training-course "AWS Cloud Architect Course") Trending Courses [PMP Certification Training Course](https://www.simplilearn.com/project-management/pmp-certification-training "PMP Certification Training Course") \| [CSM Certification Course](https://www.simplilearn.com/agile-and-scrum/csm-certification-training "CSM Certification Course") \| [Data Science with Python Course](https://www.simplilearn.com/big-data-and-analytics/python-for-data-science-training "Data Science with Python Course") \| [AWS Certification](https://www.simplilearn.com/cloud-computing/aws-solution-architect-associate-training "AWS Certification") \| [CEH Certification](https://www.simplilearn.com/cyber-security/ceh-certification "CEH Certification") \| [AZ 900 Certification](https://www.simplilearn.com/microsoft-azure-fundamentals-az-900-certification "AZ 900 Certification") \| [CompTIA Security+ Certification](https://www.simplilearn.com/comptia-security-plus-certification-training "CompTIA Security+ Certification ") \| [AZ 400 Certification](https://www.simplilearn.com/microsoft-certified-devops-engineer-expert "AZ 400 Certification") \| [SAFe Certification](https://www.simplilearn.com/agile-and-scrum/safe-agilist-certification-training "SAFe Certification") \| [CISSP Certification Training](https://www.simplilearn.com/cyber-security/cissp-certification-training "CISSP Certification Training") \| [Tableau Certification Course](https://www.simplilearn.com/tableau-training-and-data-visualization-course "Tableau Certification Course") \| [Lean Six Sigma Green Belt Certification](https://www.simplilearn.com/quality-management/lean-six-sigma-green-belt-training "Lean Six Sigma Green Belt Certification") \| [Lean Six Sigma Black Belt Certification](https://www.simplilearn.com/quality-management/lean-six-sigma-black-belt-training "Lean Six Sigma Black Belt Certification") \| [Power BI Certification Course](https://www.simplilearn.com/power-bi-certification-training-course "Power BI Certification Course") \| [Java Certification Course](https://www.simplilearn.com/mobile-and-software-development/java-javaee-soa-development-training "Java Certification Course") \| [Python Certification Training Course](https://www.simplilearn.com/mobile-and-software-development/python-development-training "Python Certification Training Course") Trending Categories [Project Management Courses](https://www.simplilearn.com/courses/project-management "Project Management Courses") \| [Online Certifications](https://www.simplilearn.com/certifications "Online Certifications") \| [Generative AI Courses](https://www.simplilearn.com/courses/generative-ai "Generative AI Courses") \| [Agile Certifications](https://www.simplilearn.com/courses/agile-and-scrum "Agile Certifications") \| [Cloud Computing Courses](https://www.simplilearn.com/courses/cloud-computing "Cloud Computing Courses") \| [Cyber Security Courses](https://www.simplilearn.com/courses/cyber-security "Cyber Security Courses") \| [EC-Council Certifications](https://www.simplilearn.com/certifications/eccouncil-certifications "EC-Council Certifications") \| [PeopleCert Certifications](https://www.simplilearn.com/certifications/peoplecert-certifications "PeopleCert Certifications") \| [Scrum Alliance Certifications](https://www.simplilearn.com/certifications/scrum-alliance-certifications "Scrum Alliance Certifications") \| [Software Development Courses](https://www.simplilearn.com/courses/software-development "Software Development Courses") \| [Web Development Courses](https://www.simplilearn.com/courses/web-development "Web Development Courses") \| [Scaled Agile Certifications](https://www.simplilearn.com/certifications/scaled-agile-certifications "Scaled Agile Certifications") \| [ISC2 Certifications](https://www.simplilearn.com/certifications/isc2-certifications "ISC2 Certifications") \| [AXELOS Certifications](https://www.simplilearn.com/certifications/axelos-courses "AXELOS Certifications") \| [ISACA Certifications](https://www.simplilearn.com/certifications/isaca-certifications "ISACA Certifications") \| [PMI Certifications](https://www.simplilearn.com/certifications/pmi-certifications "PMI Certifications") \| [CompTIA certifications](https://www.simplilearn.com/certifications/comptia-certifications "CompTIA certifications") \| [AWS Courses](https://www.simplilearn.com/courses/aws "AWS Courses") \| [Microsoft Certifications](https://www.simplilearn.com/certifications/microsoft-certification "Microsoft Certifications") \| [AI Courses](https://www.simplilearn.com/courses/ai "AI Courses") \| [Digital Marketing Courses](https://www.simplilearn.com/courses/digital-marketing "Digital Marketing Courses") Trending Resources [Python Tutorial](https://www.simplilearn.com/tutorials/python-tutorial "Python Tutorial") \| [JavaScript Tutorial](https://www.simplilearn.com/tutorials/javascript-tutorial "JavaScript Tutorial") \| [Java Tutorial](https://www.simplilearn.com/tutorials/java-tutorial "Java Tutorial") \| [Angular Tutorial](https://www.simplilearn.com/tutorials/angular-tutorial "Angular Tutorial") \| [Node.js Tutorial](https://www.simplilearn.com/tutorials/nodejs-tutorial "Node.js Tutorial") \| [Docker Tutorial](https://www.simplilearn.com/tutorials/docker-tutorial "Docker Tutorial") \| [Git Tutorial](https://www.simplilearn.com/tutorials/git-tutorial "Git Tutorial") \| [Kubernetes Tutorial](https://www.simplilearn.com/tutorials/kubernetes-tutorial "Kubernetes Tutorial") \| [Power BI Tutorial](https://www.simplilearn.com/tutorials/power-bi-tutorial "Power BI Tutorial") \| [CSS Tutorial](https://www.simplilearn.com/tutorials/css-tutorial "CSS Tutorial") OK - [Terms and Conditions](https://www.simplilearn.com/terms-and-conditions#terms-and-conditions "Terms and Conditions") - [Privacy Policy](https://www.simplilearn.com/terms-and-conditions#privacy-policy "Privacy Policy") - [Refund Policy](https://www.simplilearn.com/terms-and-conditions#refund-policy "Refund Policy") - © 2009-2026 - Simplilearn Solutions. All Rights Reserved. The certification names are the trademarks of their respective owners. smpl\_2026-04-13 - Acknowledgement - PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc. - \*All trademarks are the property of their respective owners and their inclusion does not imply endorsement or affiliation. - Career Impact Results vary based on experience and numerous factors.
Readable Markdown
The Bellman-Ford algorithm emulates the shortest paths from a single source vertex to all other vertices in a weighted digraph. It is slower than Dijkstra's algorithm for the same problem but more versatile because it can handle graphs with some edge weights that are negative numbers. Alfonso Shimbel proposed the algorithm in 1955, but it is now named after Richard Bellman and Lester Ford Jr., who brought it out in 1958 and 1956. In 1959, Edward F. Moore published a variation of the [algorithm](https://www.simplilearn.com/data-structures-and-algorithms-article "algorithm"), sometimes referred to as the Bellman-Ford–Moore algorithm. ## What Is the Bellman-Ford Algorithm? Dynamic Programming is used in the Bellman-Ford algorithm. It begins with a starting vertex and calculates the distances between other vertices that a single edge can reach. It then searches for a path with two edges, and so on. The Bellman-Ford algorithm uses the bottom-up approach. ![what-is-bellman-ford-algorithm.](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/what-is-bellman-ford-algorithm.png) Based on the "Principle of Relaxation," more accurate values gradually recovered an approximation to the proper distance until finally reaching the optimum solution. Negative weight edges can generate negative weight cycles, which reduce the total path distance by returning to the same point. ### Why Should You Be Cautious With Negative Weights? When attempting to find the shortest path, negative weight cycles may produce an incorrect result. Shortest path algorithms, such as Dijkstra's Algorithm that cannot detect such a cycle, may produce incorrect results because they may go through a negative weight cycle, reducing the path length. After learning about the Bellman-Ford algorithm, you will look at how it works in this tutorial. ## How Does the Bellman-Ford Algorithm Work? The Bellman-Ford algorithm works by grossly underestimating the length of the path from the starting vertex to all other vertices. The algorithm then iteratively relaxes those estimates by discovering new ways that are shorter than the previously overestimated paths. You can ensure that the result is optimized by repeating this process for all vertices. Step 1: Make a list of all the graph's edges. This is simple if an adjacency list represents the graph. Step 2: "V - 1" is used to calculate the number of iterations. Because the shortest distance to an edge can be adjusted V - 1 time at most, the number of iterations will increase the same number of vertices. Step 3: Begin with an arbitrary vertex and a minimum distance of zero. Because you are exaggerating the actual distances, all other nodes should be assigned infinity. For each edge u-v, relax the path lengths for the vertices: If distance\[v\] is greater than distance\[u\] + edge weight uv, then distance\[v\] = distance\[u\] + edge weight uv Step 4:If the new distance is less than the previous one, update the distance for each Edge in each iteration. The distance to each node is the total distance from the starting node to this specific node. Step 5: To ensure that all possible paths are considered, you must consider alliterations. You will end up with the shortest distance if you do this. Moving ahead with this tutorial on the Bellman-Ford algorithm, you will now learn the pseudocode for this algorithm. ## Pseudocode of the Bellman-Ford Algorithm Every Vertex's path distance must be maintained. That can be stored in a V-dimensional array, where V is the number of vertices. Not only do you need to know the length of the shortest path, but you also need to be able to find it. To accomplish this, you must map each Vertex to the Vertex that most recently updated its path length. When the algorithm is finished, you can find the path from the destination vertex to the source. function bellmanFordAlgorithm(G, s) //G is the graph and s is the source vertex for each vertex V in G dist\[V\] \<- infinite // dist is distance prev\[V\] \<- NULL // prev is previous dist\[s\] \<- 0 for each vertex V in G for each edge (u,v) in G temporaryDist \<- dist\[u\] + edgeweight(u, v) if temporaryDist \< dist\[v\] dist\[v\] \<- temporaryDist prev\[v\] \<- u for each edge (U,V) in G If dist\[U\] + edgeweight(U, V) \< dist\[V} Error: Negative Cycle Exists return dist\[\], previ\[\] As you progress through this tutorial, you will see an example of the Bellman-Ford algorithm for a better learning experience. ## An Example of Bellman-Ford Algorithm Consider the weighted graph below. ![Example-of-bellman-ford-algorithm.](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/Example-of-bellman-ford-algorithm.png) - Choose path value 0 for the source vertex and infinity for all other vertices. ![Example-of-bellman-ford-algorithm1.](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/Example-of-bellman-ford-algorithm1.png) - If the new calculated path length is less than the previous path length, go to the source vertex's neighboring Edge and relax the path length of the adjacent Vertex. ![Example-of-bellman-ford-algorithm2.](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/Example-of-bellman-ford-algorithm2.png) - This procedure must be repeated V-1 times, where V is the number of vertices in total. This happened because, in the worst-case scenario, any vertex's path length can be changed N times to an even shorter path length. ![Example-of-bellman-ford-algorithm3.](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/Example-of-bellman-ford-algorithm3.png) ![Example-of-bellman-ford-algorithm3](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/Example-of-bellman-ford-algorithm3.png) - As a result, after V-1 iterations, you find your new path lengths and can determine in case the graph has a negative cycle or not. ![Example-of-bellman-ford-algorithm5](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/Example-of-bellman-ford-algorithm5.png) You will now look at the time and space complexity of the Bellman-Ford algorithm after you have a better understanding of it. ## The Complexity of Bellman-Ford Algorithm Following is the time complexity of the bellman ford algorithm For all cases, the complexity of this algorithm will be determined by the number of edge comparisons. if temporaryDist \< dist\[v\] Edge relaxation differences depend on the graph and the sequence of looking in on edges in the graph. The algorithm may need to undergo all repetitions while updating edges, but in many cases, the result is obtained in the first few iterations, so no updates are required. dist\[v\] \<- temporaryDist - ### Worst-Case Time Complexity When you come across a negative cycle in the graph, you can have a worst-case scenario. As an example of a negative cycle, consider the following: ![worst-case-bellman-ford-algorithm.](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/worst-case-bellman-ford-algorithm.png) In a complete graph with edges between every pair of vertices, and assuming you found the shortest path in the first few iterations or repetitions but still go on with edge relaxation, you would have to relax \|E\| \* (\|E\| - 1) / 2 edges, (\|V\| - 1) number of times. The worst-case scenario in the case of a complete graph, the time complexity is as follows: O(\|V\|2) = O(E V). O(\|V\|) = O (V3) - ### Average Case Time Complexity You can reduce the worst-case running time by stopping the algorithm when no changes are made to the path values. As a result, there will be fewer iterations. Another way to improve it is to ignore any vertex V with a distance value that has not changed since the last relaxation in subsequent iterations, reducing the number of edges that need to be relaxed and increasing the number of edges with correct values after each iteration. More information is available at the link at the bottom of this post. Relaxation occurs \|V\| - 1 time for every \|E\| the number of edges, so you multiply the two and get the average, which is the quadratic time complexity of O. (E V). - ### Best Case Time Complexity ![best-case-time-complexity-in-bellman-ford-algorithm](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/best-case-time-complexity-in-bellman-ford-algorithm.png) If edge relaxation occurs from left to right in the above graph, the algorithm would only need to perform one relaxation iteration to find the shortest path, resulting in the time complexity of O(E) corresponding to the number of edges in the graph. The following is the space complexity of the bellman ford algorithm: The space complexity of the Bellman-Ford algorithm is O(V). Following that, in this Bellman-Ford algorithm tutorial, you will look at some use cases of the Bellman-Ford algorithm. ## Uses of Bellman-Ford Algorithm There are several real-world applications for the Bellman-Ford algorithm, including: - Identifying negative weight cycles - In a chemical reaction, calculate the smallest possible heat gain/loss. - Identifying the most efficient currency conversion method. You will now peek at some applications of the Bellman-Ford algorithm in this tutorial. ## Applications of the Bellman-Ford Algorithm Following are the applications of the bellman ford algorithm: - Examining a graph for the presence of negative weight cycles. - Using negative weights, find the shortest path in a graph. - Routing is a concept used in data networks. Last but not least, you will need to perform practical demonstrations of the Bellman-Ford algorithm in the [C programming language.](https://www.simplilearn.com/c-programming-article "C programming language.") ## Code Demonstration of Bellman-Ford Algorithm \#include\<stdio.h\> \#include\<stdlib.h\> \#include\<conio.h\> \#include\<string.h\> \#include\<limits.h\> struct Edges { // This structure is equal to an edge. Edge contains two endpoints. These edges are directed edges so they //contain source and destination and some weight. These 3 are elements in this structure int src, dest, wt; }; // a structure to represent a graph struct Graph { int Vertex, Edge; //Vertex is the number of vertices, and Edge is the number of edges struct Edges\* edge; // This structure contains another structure that we have already created. }; struct Graph\* designGraph(int Vertex, int Edge) { struct Graph\* graph = (struct Graph\*) malloc( sizeof(struct Graph)); //Allocating space to structure graph graph-\>Vertex = Vertex; //assigning values to structure elements that taken form user. graph-\>Edge = Edge; graph-\>edge = (struct Edges\*) malloc( graph-\>Edge \* sizeof( struct Edges ) ); //Creating "Edge" type structures inside "Graph" structure, the number of edge type structures are equal to number of edges return graph; } void Solution(int dist\[\], int n) { // This function prints the last solution printf("\\nVertex\\tDistance from Source Vertex\\n"); int i; for (i = 0; i \< n; ++i){ printf("%d \\t\\t %d\\n", i, dist\[i\]); } } void BellmanFordalgorithm(struct Graph\* graph, int src) { int Vertex = graph-\>Vertex; int Edge = graph-\>Edge; int Distance\[Vertex\]; int i,j; // This is the initial step that we know, and we initialize all distances to infinity except the source vertex. // We assign source distance as 0 for (i = 0; i \< Vertex; i++) Distance\[i\] = INT\_MAX; Distance\[src\] = 0; //The shortest path of graph that contain Vertex vertices, never contain "Veretx-1" edges. So we do here "Vertex-1" relaxations for (i = 1; i \<= Vertex-1; i++) { for (j = 0; j \< Edge; j++) { int u = graph-\>edge\[j\].src; int v = graph-\>edge\[j\].dest; int wt = graph-\>edge\[j\].wt; if (Distance\[u\] + wt \< Distance\[v\]) Distance\[v\] = Distance\[u\] + wt; } } //, up to now, the shortest path found. But BellmanFordalgorithm checks for negative edge cycles. In this step, we check for that // shortest path if the graph doesn't contain any negative weight cycle in the graph. // If we get a shorter path, then there is a negative edge cycle. for (i = 0; i \< Edge; i++) { int u = graph-\>edge\[i\].src; int v = graph-\>edge\[i\].dest; int wt = graph-\>edge\[i\].wt; if (Distance\[u\] + wt \< Distance\[v\]) printf("This graph contains negative edge cycle\\n"); } Solution(Distance, Vertex); return; } int main() { int V,E,S; //V = no.of Vertices, E = no.of Edges, S is source vertex printf("Enter number of vertices\\n"); scanf("%d",\&V); printf("Enter number of edges\\n"); scanf("%d",\&E); printf("Enter the source vertex number\\n"); scanf("%d",\&S); struct Graph\* graph = designGraph(V, E); //calling the function to allocate space to these many vertices and edges int i; for(i=0;i\<E;i++){ printf("\\nEnter edge %d properties Source, destination, weight respectively\\n",i+1); scanf("%d",\&graph-\>edge\[i\].src); scanf("%d",\&graph-\>edge\[i\].dest); scanf("%d",\&graph-\>edge\[i\].wt); } BellmanFordalgorithm(graph, S); //passing created graph and source vertex to BellmanFord Algorithm function return 0; } ### Output ![bellman-ford-algorithm-code-output](https://www.simplilearn.com/ice9/free_resources_article_thumb/Bellman%20Ford%20Algorithm/bellman-ford-algorithm-code-output.png) Now that you have reached the end of the Bellman-Ford tutorial, you will go over everything you’ve learned so far. > Advance your career as a MEAN stack developer with the [Post Graduate Program In Full Stack Web Development](https://www.simplilearn.com/certifications/full-stack-courses?source=GhPreviewCoursepages "Post Graduate Program In Full Stack Web Development"). Enroll now\! ## Next Steps In this Bellman-Ford algorithm tutorial, you looked at what the algorithm is and how it works. You studied and comprehended the Bellman-Ford algorithm step-by-step, using the example as a guide. You also learned C programming language code and the output for calculating the distance from the source vertex in a weighted graph. And you saw the time complexity for applying the algorithm and the applications and uses that you can put to use in your daily lives. Assume you're looking for a more in-depth study that goes beyond Mobile and [Software Development](https://www.simplilearn.com/what-is-a-software-developer-article "Software Development") and covers today's most in-demand [programming languages](https://www.simplilearn.com/evolution-of-programming-languages-article "programming languages") and skills. In that case, Simplilearn's [software-development](https://www.simplilearn.com/mobile-and-software-development "software-development") course is the right choice for you. Explore this globally recognized Bootcamp program. Rest assured that completing it will be the best decision you can make to enter and advance in the mobile and software development professions. Do you have any queries about this tutorial on Bellman-Ford Algorithm? Please leave them in the comments section at the bottom of this page if you do. Our experts will be happy to respond to your questions as earliest as possible\!
Shard79 (laksa)
Root Hash17406570482395038879
Unparsed URLcom,simplilearn!www,/tutorials/data-structure-tutorial/bellman-ford-algorithm s443