🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 35 (from laksa067)

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
1 day 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.programiz.com/dsa/bellman-ford-algorithm
Last Crawled2026-04-06 00:28:44 (1 day ago)
First Indexed2017-05-12 08:57:40 (8 years ago)
HTTP Status Code200
Meta TitleBellman Ford's Algorithm
Meta DescriptionBellman Ford's Algorithm is similar to Dijkstra's algorithm but it can work with graphs in which edges can have negative weights. In this tutorial, you will understand the working on Bellman Ford's Algorithm in Python, Java and C/C++.
Meta Canonicalnull
Boilerpipe Text
It is similar to Dijkstra's algorithm but it can work with graphs in which edges can have negative weights. Why would one ever have edges with negative weights in real life? Negative weight edges might seem useless at first but they can explain a lot of phenomena like cashflow, the heat released/absorbed in a chemical reaction, etc. For instance, if there are different ways to reach from one chemical A to another chemical B, each method will have sub-reactions involving both heat dissipation and absorption. If we want to find the set of reactions where minimum energy is required, then we will need to be able to factor in the heat absorption as negative weights and heat dissipation as positive weights. Why do we need to be careful with negative weights? Negative weight edges can create negative weight cycles i.e. a cycle that will reduce the total path distance by coming back to the same point. Negative weight cycles can give an incorrect result when trying to find out the shortest path Shortest path algorithms like Dijkstra's Algorithm that aren't able to detect such a cycle can give an incorrect result because they can go through a negative weight cycle and reduce the path length. How Bellman Ford's algorithm works Bellman Ford algorithm works by overestimating the length of the path from the starting vertex to all other vertices. Then it iteratively relaxes those estimates by finding new paths that are shorter than the previously overestimated paths. By doing this repeatedly for all vertices, we can guarantee that the result is optimized. Step-1 for Bellman Ford's algorithm Step-2 for Bellman Ford's algorithm Step-3 for Bellman Ford's algorithm Note: To relax the path, an edge(U, V), if distance(U) + edge_weight(U,V) < distance(V) , assign distance(V) = distance(U) + edge_weight(U,V) . Step-4 for Bellman Ford's algorithm Step-5 for Bellman Ford's algorithm Step-6 for Bellman Ford's algorithm Bellman Ford Pseudocode We need to maintain the path distance of every vertex. We can store that in an array of size v, where v is the number of vertices. We also want to be able to get the shortest path, not only know the length of the shortest path. For this, we map each vertex to the vertex that last updated its path length. Once the algorithm is over, we can backtrack from the destination vertex to the source vertex to find the path. function bellmanFord(G, S) for each vertex V in G distance[V] <- infinite previous[V] <- NULL distance[S] <- 0 for each vertex V in G for each edge (U,V) in G tempDistance <- distance[U] + edge_weight(U, V) if tempDistance < distance[V] distance[V] <- tempDistance previous[V] <- U for each edge (U,V) in G if distance[U] + edge_weight(U, V) < distance[V] Error: Negative Cycle Exists return distance[], previous[] Bellman Ford vs Dijkstra Bellman Ford's algorithm and Dijkstra's algorithm are very similar in structure. While Dijkstra looks only to the immediate neighbors of a vertex, Bellman goes through each edge in every iteration. Bellman Ford's Algorithm vs Dijkstra's Algorithm Python, Java and C/C++ Examples # Bellman Ford Algorithm in Python class Graph: def __init__(self, vertices): self.V = vertices # Total number of vertices in the graph self.graph = [] # Array of edges # Add edges def add_edge(self, s, d, w): self.graph.append([s, d, w]) # Print the solution def print_solution(self, dist): print("Vertex Distance from Source") for i in range(self.V - 1): print("{0}\t\t{1}".format(i, dist[i])) def bellman_ford(self, src): # Step 1: fill the distance array and predecessor array dist = [float("Inf")] * self.V # Mark the source vertex dist[src] = 0 # Step 2: relax edges |V| - 1 times for _ in range(self.V - 1): for s, d, w in self.graph: if dist[s] != float("Inf") and dist[s] + w < dist[d]: dist[d] = dist[s] + w # Step 3: detect negative cycle # if value changes then we have a negative cycle in the graph # and we cannot find the shortest distances for s, d, w in self.graph: if dist[s] != float("Inf") and dist[s] + w < dist[d]: print("Graph contains negative weight cycle") return # No negative weight cycle found! # Print the distance and predecessor array self.print_solution(dist) g = Graph(5) g.add_edge(0, 1, 5) g.add_edge(0, 2, 4) g.add_edge(1, 3, 3) g.add_edge(2, 1, 6) g.add_edge(3, 2, 2) g.bellman_ford(0) // Bellman Ford Algorithm in Java class CreateGraph { // CreateGraph - it consists of edges class CreateEdge { int s, d, w; CreateEdge() { s = d = w = 0; } }; int V, E; CreateEdge edge[]; // Creates a graph with V vertices and E edges CreateGraph(int v, int e) { V = v; E = e; edge = new CreateEdge[e]; for (int i = 0; i < e; ++i) edge[i] = new CreateEdge(); } void BellmanFord(CreateGraph graph, int s) { int V = graph.V, E = graph.E; int dist[] = new int[V]; // Step 1: fill the distance array and predecessor array for (int i = 0; i < V; ++i) dist[i] = Integer.MAX_VALUE; // Mark the source vertex dist[s] = 0; // Step 2: relax edges |V| - 1 times for (int i = 1; i < V; ++i) { for (int j = 0; j < E; ++j) { // Get the edge data int u = graph.edge[j].s; int v = graph.edge[j].d; int w = graph.edge[j].w; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) dist[v] = dist[u] + w; } } // Step 3: detect negative cycle // if value changes then we have a negative cycle in the graph // and we cannot find the shortest distances for (int j = 0; j < E; ++j) { int u = graph.edge[j].s; int v = graph.edge[j].d; int w = graph.edge[j].w; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) { System.out.println("CreateGraph contains negative w cycle"); return; } } // No negative w cycle found! // Print the distance and predecessor array printSolution(dist, V); } // Print the solution void printSolution(int dist[], int V) { System.out.println("Vertex Distance from Source"); for (int i = 0; i < V - 1; ++i) System.out.println(i + "\t\t" + dist[i]); } public static void main(String[] args) { int V = 5; // Total vertices int E = 5; // Total Edges CreateGraph graph = new CreateGraph(V, E); // edge 0 --> 1 graph.edge[0].s = 0; graph.edge[0].d = 1; graph.edge[0].w = 5; // edge 0 --> 2 graph.edge[1].s = 0; graph.edge[1].d = 2; graph.edge[1].w = 4; // edge 1 --> 3 graph.edge[2].s = 1; graph.edge[2].d = 3; graph.edge[2].w = 3; // edge 2 --> 1 graph.edge[3].s = 2; graph.edge[3].d = 1; graph.edge[3].w = 6; // edge 3 --> 2 graph.edge[4].s = 3; graph.edge[4].d = 2; graph.edge[4].w = 2; graph.BellmanFord(graph, 0); // 0 is the source vertex } } // Bellman Ford Algorithm in C #include <stdio.h> #include <stdlib.h> #define INFINITY 99999 //struct for the edges of the graph struct Edge { int u; //start vertex of the edge int v; //end vertex of the edge int w; //weight of the edge (u,v) }; //Graph - it consists of edges struct Graph { int V; //total number of vertices in the graph int E; //total number of edges in the graph struct Edge *edge; //array of edges }; void bellmanford(struct Graph *g, int source); void display(int arr[], int size); int main(void) { //create graph struct Graph *g = (struct Graph *)malloc(sizeof(struct Graph)); g->V = 4; //total vertices g->E = 5; //total edges //array of edges for graph g->edge = (struct Edge *)malloc(g->E * sizeof(struct Edge)); //------- adding the edges of the graph /* edge(u, v) where u = start vertex of the edge (u,v) v = end vertex of the edge (u,v) w is the weight of the edge (u,v) */ //edge 0 --> 1 g->edge[0].u = 0; g->edge[0].v = 1; g->edge[0].w = 5; //edge 0 --> 2 g->edge[1].u = 0; g->edge[1].v = 2; g->edge[1].w = 4; //edge 1 --> 3 g->edge[2].u = 1; g->edge[2].v = 3; g->edge[2].w = 3; //edge 2 --> 1 g->edge[3].u = 2; g->edge[3].v = 1; g->edge[3].w = 6; //edge 3 --> 2 g->edge[4].u = 3; g->edge[4].v = 2; g->edge[4].w = 2; bellmanford(g, 0); //0 is the source vertex return 0; } void bellmanford(struct Graph *g, int source) { //variables int i, j, u, v, w; //total vertex in the graph g int tV = g->V; //total edge in the graph g int tE = g->E; //distance array //size equal to the number of vertices of the graph g int d[tV]; //predecessor array //size equal to the number of vertices of the graph g int p[tV]; //step 1: fill the distance array and predecessor array for (i = 0; i < tV; i++) { d[i] = INFINITY; p[i] = 0; } //mark the source vertex d[source] = 0; //step 2: relax edges |V| - 1 times for (i = 1; i <= tV - 1; i++) { for (j = 0; j < tE; j++) { //get the edge data u = g->edge[j].u; v = g->edge[j].v; w = g->edge[j].w; if (d[u] != INFINITY && d[v] > d[u] + w) { d[v] = d[u] + w; p[v] = u; } } } //step 3: detect negative cycle //if value changes then we have a negative cycle in the graph //and we cannot find the shortest distances for (i = 0; i < tE; i++) { u = g->edge[i].u; v = g->edge[i].v; w = g->edge[i].w; if (d[u] != INFINITY && d[v] > d[u] + w) { printf("Negative weight cycle detected!\n"); return; } } //No negative weight cycle found! //print the distance and predecessor array printf("Distance array: "); display(d, tV); printf("Predecessor array: "); display(p, tV); } void display(int arr[], int size) { int i; for (i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // Bellman Ford Algorithm in C++ #include <bits/stdc++.h> // Struct for the edges of the graph struct Edge { int u; //start vertex of the edge int v; //end vertex of the edge int w; //w of the edge (u,v) }; // Graph - it consists of edges struct Graph { int V; // Total number of vertices in the graph int E; // Total number of edges in the graph struct Edge* edge; // Array of edges }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = new Graph; graph->V = V; // Total Vertices graph->E = E; // Total edges // Array of edges for graph graph->edge = new Edge[E]; return graph; } // Printing the solution void printArr(int arr[], int size) { int i; for (i = 0; i < size - 1; i++) { printf("%d ", arr[i]); } printf("\n"); } void BellmanFord(struct Graph* graph, int u) { int V = graph->V; int E = graph->E; int dist[V]; // Step 1: fill the distance array and predecessor array for (int i = 0; i < V; i++) dist[i] = INT_MAX; // Mark the source vertex dist[u] = 0; // Step 2: relax edges |V| - 1 times for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { // Get the edge data int u = graph->edge[j].u; int v = graph->edge[j].v; int w = graph->edge[j].w; if (dist[u] != INT_MAX && dist[u] + w < dist[v]) dist[v] = dist[u] + w; } } // Step 3: detect negative cycle // if value changes then we have a negative cycle in the graph // and we cannot find the shortest distances for (int i = 0; i < E; i++) { int u = graph->edge[i].u; int v = graph->edge[i].v; int w = graph->edge[i].w; if (dist[u] != INT_MAX && dist[u] + w < dist[v]) { printf("Graph contains negative w cycle"); return; } } // No negative weight cycle found! // Print the distance and predecessor array printArr(dist, V); return; } int main() { // Create a graph int V = 5; // Total vertices int E = 5; // Total edges // Array of edges for graph struct Graph* graph = createGraph(V, E); //------- adding the edges of the graph /* edge(u, v) where u = start vertex of the edge (u,v) v = end vertex of the edge (u,v) w is the weight of the edge (u,v) */ //edge 0 --> 1 graph->edge[0].u = 0; graph->edge[0].v = 1; graph->edge[0].w = 5; //edge 0 --> 2 graph->edge[1].u = 0; graph->edge[1].v = 2; graph->edge[1].w = 4; //edge 1 --> 3 graph->edge[2].u = 1; graph->edge[2].v = 3; graph->edge[2].w = 3; //edge 2 --> 1 graph->edge[3].u = 2; graph->edge[3].v = 1; graph->edge[3].w = 6; //edge 3 --> 2 graph->edge[4].u = 3; graph->edge[4].v = 2; graph->edge[4].w = 2; BellmanFord(graph, 0); //0 is the source vertex return 0; } Bellman Ford's Complexity Time Complexity Best Case Complexity O(E) Average Case Complexity O(VE) Worst Case Complexity O(VE) Space Complexity And, the space complexity is O(V) . Bellman Ford's Algorithm Applications For calculating shortest paths in routing algorithms For finding the shortest path
Markdown
![](https://www.facebook.com/tr?id=123000288571689&ev=PageView&noscript=1) [Stop copy pasting code you don't actually understand Build the coding confidence you need to become a developer companies will fight for Stop copy pasting code you don't actually understand Ends in Start FREE Trial Start FREE Trial Start FREE Trial Start FREE Trial](https://programiz.pro/?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=programiz&utm_content=default_banner&utm_term=sticky_banner_launch "Start FREE Trial") [Stop copy pasting code you don't actually understand Build the coding confidence you need to become a developer companies will fight for Stop copy pasting code you don't actually understand Ends in Start FREE Trial Start FREE Trial Start FREE Trial Start FREE Trial](https://programiz.pro/?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=programiz&utm_content=default_banner&utm_term=sticky_banner_launch "Start FREE Trial") [![Programiz](https://cdn.programiz.com/sites/tutorial2program/files/sp_logo.svg) ![Programiz](https://cdn.programiz.com/sites/tutorial2program/files/pc_logo.svg)](https://www.programiz.com/ "Programiz") [Tutorials](https://www.programiz.com/dsa/bellman-ford-algorithm "Programming Tutorials") [Examples]("Programming Examples") [![Programiz Pro Logo](https://www.programiz.com/sites/all/themes/programiz/assets/programiz-pro-mini-logo.svg) Courses](https://www.programiz.com/dsa/bellman-ford-algorithm "Learn to Code Interactively") [Try Programiz PRO](https://programiz.pro/course/dsa-with-python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_dsa&utm_term=nav_floating_button "Try Programiz PRO") Course Index Tutorials Courses [Python]("Python") [JavaScript]("JavaScript") [TypeScript]("TypeScript") [SQL]("SQL") [HTML]("HTML") [CSS]("CSS") [C]("C") [C++]("C++") [Java]("Java") [R]("R") [Ruby]("Ruby") [RUST]("RUST") [Golang]("Golang") [Kotlin]("Kotlin") [Swift]("Swift") [C\#]("C#") [DSA]("DSA") Become a certified Python programmer. [ENROLL](https://programiz.pro/learn/master-python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner) #### Popular Tutorials [Getting Started With Python](https://www.programiz.com/python-programming/getting-started?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Getting Started With Python") [Python if Statement](https://www.programiz.com/python-programming/if-elif-else?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python if Statement") [while Loop in Python](https://www.programiz.com/python-programming/while-loop?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "while Loop in Python") [Python Lists](https://www.programiz.com/python-programming/list?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python Lists") [Dictionaries in Python](https://www.programiz.com/python-programming/dictionary?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Dictionaries in Python") [Start Learning Python](https://www.programiz.com/python-programming?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python Tutorials") #### Popular Examples [Add two numbers](https://www.programiz.com/python-programming/examples/add-number?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Add two numbers") [Check prime number](https://www.programiz.com/python-programming/examples/prime-number?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Check prime number") [Find the factorial of a number](https://www.programiz.com/python-programming/examples/factorial?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Find the factorial of a number") [Print the Fibonacci sequence](https://www.programiz.com/python-programming/examples/fibonacci-sequence?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Print the Fibonacci sequence") [Check leap year](https://www.programiz.com/python-programming/examples/leap-year?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Check leap year") [Explore Python Examples](https://www.programiz.com/python-programming/examples?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python Examples") #### Reference Materials [Built-in Functions](https://www.programiz.com/python-programming/methods/built-in?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Built-in Functions") [List Methods](https://www.programiz.com/python-programming/methods/list?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "List Methods") [Dictionary Methods](https://www.programiz.com/python-programming/methods/dictionary?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Dictionary Methods") [String Methods](https://www.programiz.com/python-programming/methods/string?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "String Methods") [View all](https://www.programiz.com/python-programming/methods?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python References") ![Programiz Pro Logo](https://www.programiz.com/sites/all/themes/programiz/assets/pro-images/programiz-pro-logo.svg) Created with over a decade of experience. - [Learn]("Learn") - [Practice]("Practice") - [Compete]("Compete") [Learn Python](https://programiz.pro/learn/master-python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_programiz-pro_courses "Learn Python") [Learn HTML](https://programiz.pro/course/learn-html?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_html&utm_term=nav_programiz-pro_courses "Learn HTML") [Learn JavaScript](https://programiz.pro/learn/master-javascript?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_javascript&utm_term=nav_programiz-pro_courses "Learn JavaScript") [Learn SQL](https://programiz.pro/course/learn-sql-basics?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_sql&utm_term=nav_programiz-pro_courses "Learn SQL") [Learn DSA](https://programiz.pro/course/dsa-with-python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_dsa&utm_term=nav_programiz-pro_courses "Learn DSA") [Learn C](https://programiz.pro/learn/master-c-programming?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_c&utm_term=nav_programiz-pro_courses "Learn C") [Learn C++](https://programiz.pro/learn/master-cpp?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_cpp&utm_term=nav_programiz-pro_courses "Learn C++") [Learn Java](https://programiz.pro/learn/master-java?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_java&utm_term=nav_programiz-pro_courses "Learn Java") [View all Courses on ![Programiz Pro Logo](https://www.programiz.com/sites/all/themes/programiz/assets/programiz-pro-mini-logo.svg)](https://programiz.pro/courses?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "View all Courses on PRO") [Python Basics](https://programiz.pro/course/practice-python-basics?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_python&utm_term=nav_programiz-pro_practice_courses "Python Basics") [Python Intermediate](https://programiz.pro/course/practice-python-intermediate?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_python&utm_term=nav_programiz-pro_practice_courses "Python Intermediate") [C++ Basics](https://programiz.pro/course/practice-cpp-basics?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_cpp&utm_term=nav_programiz-pro_practice_courses "C++ Basics") [C++ Intermediate](https://programiz.pro/course/practice-cpp-intermediate?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_cpp&utm_term=nav_programiz-pro_practice_courses "C++ Intermediate") [C++ OOP](https://programiz.pro/course/practice-cpp-oop?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_cpp&utm_term=nav_programiz-pro_practice_courses "C++ OOP") [C Programming](https://programiz.pro/course/practice-c-programming?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_c&utm_term=nav_programiz-pro_practice_courses "C Programming") [Java Basics](https://programiz.pro/course/practice-java-basics?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_java&utm_term=nav_programiz-pro_practice_courses "Java Basics") [Java Intermediate](https://programiz.pro/course/practice-java-intermediate?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_java&utm_term=nav_programiz-pro_practice_courses "Java Intermediate") [Java OOP](https://programiz.pro/course/practice-java-oop?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=practice_course_promotion&utm_content=interests_learn_java&utm_term=nav_programiz-pro_practice_courses "Java OOP") [View all Courses on ![Programiz Pro Logo](https://www.programiz.com/sites/all/themes/programiz/assets/programiz-pro-mini-logo.svg)](https://programiz.pro/courses?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "View all Courses on PRO") [Python Challenges](https://programiz.pro/community-challenges/python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_python&utm_term=nav_programiz-pro_challenges "Python Challenges") [JavaScript Challenges](https://programiz.pro/community-challenges/javascript?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_javascript&utm_term=nav_programiz-pro_challenges "JavaScript Challenges") [Java Challenges](https://programiz.pro/community-challenges/java?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_java&utm_term=nav_programiz-pro_challenges "Java Challenges") [C++ Challenges](https://programiz.pro/community-challenges/cpp?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_cpp&utm_term=nav_programiz-pro_challenges "C++ Challenges") [C Challenges](https://programiz.pro/community-challenges/c?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_c&utm_term=nav_programiz-pro_challenges "C Challenges") [View all Challenges on ![Programiz Pro Logo](https://www.programiz.com/sites/all/themes/programiz/assets/programiz-pro-mini-logo.svg)](https://programiz.pro/community-challenges?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "View all Challenges on PRO") [Learn]() [Practice]() [Compete]() #### Certification Courses Created with over a decade of experience and thousands of feedback. [Learn Python](https://programiz.pro/learn/master-python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_python&utm_term=nav_programiz-pro_challenges "Learn Python") [Learn HTML](https://programiz.pro/course/learn-html?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_html&utm_term=nav_programiz-pro_challenges "Learn HTML") [Learn JavaScript](https://programiz.pro/learn/master-javascript?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_javascript&utm_term=nav_programiz-pro_challenges "Learn JavaScript") [Learn SQL](https://programiz.pro/course/learn-sql-basics?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_sql&utm_term=nav_programiz-pro_challenges "Learn SQL") [Learn DSA](https://programiz.pro/course/dsa-with-python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_dsa&utm_term=nav_programiz-pro_challenges "Learn DSA") [View all Courses on ![Programiz Pro Logo](https://www.programiz.com/sites/all/themes/programiz/assets/programiz-pro-mini-logo.svg)](https://programiz.pro/courses?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "View all Courses on PRO") [Learn C](https://programiz.pro/learn/master-c-programming?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_c&utm_term=nav_programiz-pro_challenges "Learn C") [Learn C++](https://programiz.pro/learn/master-cpp?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_cpp&utm_term=nav_programiz-pro_challenges "Learn C++") [Learn Java](https://programiz.pro/learn/master-java?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=challenge_promotion&utm_content=interests_learn_java&utm_term=nav_programiz-pro_challenges "Learn Java") [Python]("Python") [JavaScript]("JavaScript") [TypeScript]("TypeScript") [SQL]("SQL") [HTML]("HTML") [CSS]("CSS") [C]("C") [C++]("C++") [Java]("Java") [More languages]("More languages") ### Become a certified Python programmer. [Try Programiz PRO\!](https://programiz.pro/learn/master-python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner) #### Popular Tutorials [Getting Started With Python](https://www.programiz.com/python-programming/getting-started?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Getting Started With Python") [Python if Statement](https://www.programiz.com/python-programming/if-elif-else?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python if Statement") [while Loop in Python](https://www.programiz.com/python-programming/while-loop?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "while Loop in Python") [Python Lists](https://www.programiz.com/python-programming/list?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python Lists") [Dictionaries in Python](https://www.programiz.com/python-programming/dictionary?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Dictionaries in Python") [Start Learning Python](https://www.programiz.com/python-programming?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python tutorials") [All Python Tutorials](https://www.programiz.com/python-programming?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "All Python tutorials") #### Reference Materials [Built-in Functions](https://www.programiz.com/python-programming/methods/built-in?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Built-in Functions") [List Methods](https://www.programiz.com/python-programming/methods/list?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "List Methods") [Dictionary Methods](https://www.programiz.com/python-programming/methods/dictionary?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Dictionary Methods") [String Methods](https://www.programiz.com/python-programming/methods/string?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "String Methods") [View all](https://www.programiz.com/python-programming/methods?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_tutorials_banner "Python References") [Python]("Python") [JavaScript]("JavaScript") [C]("C") [C++]("C++") [Java]("Java") [R]("R") [Kotlin]("Kotlin") Become a certified Python programmer. [Try Programiz PRO\!](https://programiz.pro/learn/master-python?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_examples_banner) #### Popular Examples [Add two numbers](https://www.programiz.com/python-programming/examples/add-number?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_examples_banner "Add two numbers") [Check prime number](https://www.programiz.com/python-programming/examples/prime-number?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_examples_banner "Check prime number") [Find the factorial of a number](https://www.programiz.com/python-programming/examples/factorial?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_examples_banner "Find the factorial of a number") [Print the Fibonacci sequence](https://www.programiz.com/python-programming/examples/fibonacci-sequence?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_examples_banner "Print the Fibonacci sequence") [Check leap year](https://www.programiz.com/python-programming/examples/leap-year?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_examples_banner "Check leap year") [All Python Examples](https://www.programiz.com/python-programming/examples?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=course_promotion&utm_content=interests_learn_python&utm_term=nav_examples_banner "Python Examples") - ### DSA Introduction - [Getting Started with DSA](https://www.programiz.com/dsa/getting-started "Getting Started with DSA") - [What is an algorithm?](https://www.programiz.com/dsa/algorithm "Algorithms in Programming") - [Data Structure and Types](https://www.programiz.com/dsa/data-structure-types "Data Structure and Types") - [Why learn DSA?](https://www.programiz.com/dsa/why-algorithms "Why learn DSA?") - [Asymptotic Notations](https://www.programiz.com/dsa/asymptotic-notations "Asymptotic Notations") - [Master Theorem](https://www.programiz.com/dsa/master-theorem "Master Theorem") - [Divide and Conquer Algorithm](https://www.programiz.com/dsa/divide-and-conquer "Divide and Conquer Algorithm") - ### Data Structures (I) - [Stack](https://www.programiz.com/dsa/stack "Stack Data Structure") - [Queue](https://www.programiz.com/dsa/queue "Queue Data Structure") - [Types of Queue](https://www.programiz.com/dsa/types-of-queue "Types of Queue") - [Circular Queue](https://www.programiz.com/dsa/circular-queue "Circular Queue") - [Priority Queue](https://www.programiz.com/dsa/priority-queue "Priority Queue") - [Deque](https://www.programiz.com/dsa/deque "Deque") - ### Data Structures (II) - [Linked List](https://www.programiz.com/dsa/linked-list "Linked List") - [Linked List Operations](https://www.programiz.com/dsa/linked-list-operations "Linked list operations") - [Types of Linked List](https://www.programiz.com/dsa/linked-list-types "Types of Linked List") - [Hash Table](https://www.programiz.com/dsa/hash-table "Hash Table") - [Heap Data Structure](https://www.programiz.com/dsa/heap-data-structure "Heap Data Structure") - [Fibonacci Heap](https://www.programiz.com/dsa/fibonacci-heap "Fibonacci Heap") - [Decrease Key and Delete Node Operations on a Fibonacci Heap](https://www.programiz.com/dsa/decrease-key-and-delete-node-from-a-fibonacci-heap "Decrease Key and Delete Node Operations on a Fibonacci Heap") - ### Tree based DSA (I) - [Tree Data Structure](https://www.programiz.com/dsa/trees "Tree Data Structure") - [Tree Traversal](https://www.programiz.com/dsa/tree-traversal "Tree Traversal") - [Binary Tree](https://www.programiz.com/dsa/binary-tree "Binary Tree") - [Full Binary Tree](https://www.programiz.com/dsa/full-binary-tree "Full Binary Tree") - [Perfect Binary Tree](https://www.programiz.com/dsa/perfect-binary-tree "Perfect Binary Tree") - [Complete Binary Tree](https://www.programiz.com/dsa/complete-binary-tree "Complete Binary Tree") - [Balanced Binary Tree](https://www.programiz.com/dsa/balanced-binary-tree "Balanced Binary Tree") - [Binary Search Tree](https://www.programiz.com/dsa/binary-search-tree "Binary Search Tree") - [AVL Tree](https://www.programiz.com/dsa/avl-tree "AVL Tree") - ### Tree based DSA (II) - [B Tree](https://www.programiz.com/dsa/b-tree "B Tree") - [Insertion in a B-tree](https://www.programiz.com/dsa/insertion-into-a-b-tree "Insertion in a B-tree") - [Deletion from a B-tree](https://www.programiz.com/dsa/deletion-from-a-b-tree "Deletion from a B-tree") - [B+ Tree](https://www.programiz.com/dsa/b-plus-tree "B+ Tree") - [Insertion on a B+ Tree](https://www.programiz.com/dsa/insertion-on-a-b-plus-tree "Insertion on a B+ Tree") - [Deletion from a B+ Tree](https://www.programiz.com/dsa/deletion-from-a-b-plus-tree "Deletion from a B+ Tree") - [Red-Black Tree](https://www.programiz.com/dsa/red-black-tree "Red-Black Tree") - [Red-Black Tree Insertion](https://www.programiz.com/dsa/insertion-in-a-red-black-tree "Insertion in a Red-Black Tree") - [Red-Black Tree Deletion](https://www.programiz.com/dsa/deletion-from-a-red-black-tree "Deletion From a Red-Black Tree") - ### Graph based DSA - [Graph Data Structure](https://www.programiz.com/dsa/graph "Graph Data Structure") - [Spanning Tree](https://www.programiz.com/dsa/spanning-tree-and-minimum-spanning-tree "Spanning Tree") - [Strongly Connected Components](https://www.programiz.com/dsa/strongly-connected-components "Strongly Connected Components") - [Adjacency Matrix](https://www.programiz.com/dsa/graph-adjacency-matrix "Adjacency Matrix") - [Adjacency List](https://www.programiz.com/dsa/graph-adjacency-list "Adjacency List") - [DFS Algorithm](https://www.programiz.com/dsa/graph-dfs "DFS Algorithm") - [Breadth-first Search](https://www.programiz.com/dsa/graph-bfs "Breadth-first Search") - [Bellman Ford's Algorithm](https://www.programiz.com/dsa/bellman-ford-algorithm "Bellman Ford's Algorithm") - ### Sorting and Searching Algorithms - [Bubble Sort](https://www.programiz.com/dsa/bubble-sort "Bubble Sort") - [Selection Sort](https://www.programiz.com/dsa/selection-sort "Selection Sort") - [Insertion Sort](https://www.programiz.com/dsa/insertion-sort "Insertion Sort") - [Merge Sort](https://www.programiz.com/dsa/merge-sort "Swift Ternary Conditional Operator") - [Quicksort](https://www.programiz.com/dsa/quick-sort "Quicksort") - [Counting Sort](https://www.programiz.com/dsa/counting-sort "Counting Sort") - [Radix Sort](https://www.programiz.com/dsa/radix-sort "Radix Sort") - [Bucket Sort](https://www.programiz.com/dsa/bucket-sort "Bucket Sort") - [Heap Sort](https://www.programiz.com/dsa/heap-sort "Heap Sort") - [Shell Sort](https://www.programiz.com/dsa/shell-sort "Shell Sort") - [Linear Search](https://www.programiz.com/dsa/linear-search "Linear Search") - [Binary Search](https://www.programiz.com/dsa/binary-search "Binary Search") - ### Greedy Algorithms - [Greedy Algorithm](https://www.programiz.com/dsa/greedy-algorithm "Greedy Algorithm") - [Ford-Fulkerson Algorithm](https://www.programiz.com/dsa/ford-fulkerson-algorithm "Ford-Fulkerson Algorithm") - [Dijkstra's Algorithm](https://www.programiz.com/dsa/dijkstra-algorithm "Dijkstra's Algorithm") - [Kruskal's Algorithm](https://www.programiz.com/dsa/kruskal-algorithm "Kruskal's Algorithm") - [Prim's Algorithm](https://www.programiz.com/dsa/prim-algorithm "Prim's Algorithm") - [Huffman Coding](https://www.programiz.com/dsa/huffman-coding "Huffman Coding") - ### Dynamic Programming - [Dynamic Programming](https://www.programiz.com/dsa/dynamic-programming "Dynamic Programming") - [Floyd-Warshall Algorithm](https://www.programiz.com/dsa/floyd-warshall-algorithm "Floyd-Warshall Algorithm") - [Longest Common Sequence](https://www.programiz.com/dsa/longest-common-subsequence "Longest Common Sequence") - ### Other Algorithms - [Backtracking Algorithm](https://www.programiz.com/dsa/backtracking-algorithm "Backtracking Algorithm") - [Rabin-Karp Algorithm](https://www.programiz.com/dsa/rabin-karp-algorithm "Rabin-Karp Algorithm") ### DSA Tutorials - [Graph Data Stucture](https://www.programiz.com/dsa/graph) - [Prim's Algorithm](https://www.programiz.com/dsa/prim-algorithm) - [Dijkstra's Algorithm](https://www.programiz.com/dsa/dijkstra-algorithm) - [Kruskal's Algorithm](https://www.programiz.com/dsa/kruskal-algorithm) - [Adjacency List](https://www.programiz.com/dsa/graph-adjacency-list) - [Floyd-Warshall Algorithm](https://www.programiz.com/dsa/floyd-warshall-algorithm) [![](https://www.programiz.com/sites/tutorial2program/files/dsa-1.png)](https://programiz.pro/dsa-with-visualizer?utm_source=programiz.com&utm_medium=referral&utm_campaign=dsa_with_visualizer_launch_2025&utm_content=interests_learn_dsa&utm_term=top-most-ad-spot-dsa-1) # Bellman Ford's Algorithm It is similar to [Dijkstra's algorithm](https://www.programiz.com/dsa/dijkstra-algorithm) but it can work with graphs in which edges can have negative weights. *** ## Why would one ever have edges with negative weights in real life? Negative weight edges might seem useless at first but they can explain a lot of phenomena like cashflow, the heat released/absorbed in a chemical reaction, etc. For instance, if there are different ways to reach from one chemical A to another chemical B, each method will have sub-reactions involving both heat dissipation and absorption. If we want to find the set of reactions where minimum energy is required, then we will need to be able to factor in the heat absorption as negative weights and heat dissipation as positive weights. *** ## Why do we need to be careful with negative weights? Negative weight edges can create negative weight cycles i.e. a cycle that will reduce the total path distance by coming back to the same point. ![negative weight cycles can give an incorrect result when trying to find out the shortest path](https://cdn.programiz.com/sites/tutorial2program/files/negative-weight-cycle_1.png) Negative weight cycles can give an incorrect result when trying to find out the shortest path Shortest path algorithms like Dijkstra's Algorithm that aren't able to detect such a cycle can give an incorrect result because they can go through a negative weight cycle and reduce the path length. *** ## How Bellman Ford's algorithm works Bellman Ford algorithm works by overestimating the length of the path from the starting vertex to all other vertices. Then it iteratively relaxes those estimates by finding new paths that are shorter than the previously overestimated paths. By doing this repeatedly for all vertices, we can guarantee that the result is optimized. ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-1.png) Step-1 for Bellman Ford's algorithm ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-2.png) Step-2 for Bellman Ford's algorithm ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-3.png) Step-3 for Bellman Ford's algorithm **Note:** To relax the path, an edge(U, V), if `distance(U) + edge_weight(U,V)` \< `distance(V)`, assign `distance(V)` = `distance(U) + edge_weight(U,V)`. ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-4.png) Step-4 for Bellman Ford's algorithm ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-5.png) Step-5 for Bellman Ford's algorithm ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-6.png) Step-6 for Bellman Ford's algorithm *** ## Bellman Ford Pseudocode We need to maintain the path distance of every vertex. We can store that in an array of size v, where v is the number of vertices. We also want to be able to get the shortest path, not only know the length of the shortest path. For this, we map each vertex to the vertex that last updated its path length. Once the algorithm is over, we can backtrack from the destination vertex to the source vertex to find the path. ``` function bellmanFord(G, S) for each vertex V in G distance[V] <- infinite previous[V] <- NULL distance[S] <- 0 for each vertex V in G for each edge (U,V) in G tempDistance <- distance[U] + edge_weight(U, V) if tempDistance < distance[V] distance[V] <- tempDistance previous[V] <- U for each edge (U,V) in G if distance[U] + edge_weight(U, V) < distance[V] Error: Negative Cycle Exists return distance[], previous[] ``` *** ## Bellman Ford vs Dijkstra Bellman Ford's algorithm and Dijkstra's algorithm are very similar in structure. While Dijkstra looks only to the immediate neighbors of a vertex, Bellman goes through each edge in every iteration. ![Dijkstra's vs Bellman Ford's Algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-vs-dijkstra.jpg) Bellman Ford's Algorithm vs Dijkstra's Algorithm *** ## Python, Java and C/C++ Examples [Python](https://www.programiz.com/dsa/bellman-ford-algorithm#python-code) [Java](https://www.programiz.com/dsa/bellman-ford-algorithm#java-code) [C](https://www.programiz.com/dsa/bellman-ford-algorithm#c-code) [C++](https://www.programiz.com/dsa/bellman-ford-algorithm#cpp-code) ``` # Bellman Ford Algorithm in Python class Graph: def __init__(self, vertices): self.V = vertices # Total number of vertices in the graph self.graph = [] # Array of edges # Add edges def add_edge(self, s, d, w): self.graph.append([s, d, w]) # Print the solution def print_solution(self, dist): print("Vertex Distance from Source") for i in range(self.V - 1): print("{0}\t\t{1}".format(i, dist[i])) def bellman_ford(self, src): # Step 1: fill the distance array and predecessor array dist = [float("Inf")] * self.V # Mark the source vertex dist[src] = 0 # Step 2: relax edges |V| - 1 times for _ in range(self.V - 1): for s, d, w in self.graph: if dist[s] != float("Inf") and dist[s] + w < dist[d]: dist[d] = dist[s] + w # Step 3: detect negative cycle # if value changes then we have a negative cycle in the graph # and we cannot find the shortest distances for s, d, w in self.graph: if dist[s] != float("Inf") and dist[s] + w < dist[d]: print("Graph contains negative weight cycle") return # No negative weight cycle found! # Print the distance and predecessor array self.print_solution(dist) g = Graph(5) g.add_edge(0, 1, 5) g.add_edge(0, 2, 4) g.add_edge(1, 3, 3) g.add_edge(2, 1, 6) g.add_edge(3, 2, 2) g.bellman_ford(0) ``` ``` // Bellman Ford Algorithm in Java class CreateGraph { // CreateGraph - it consists of edges class CreateEdge { int s, d, w; CreateEdge() { s = d = w = 0; } }; int V, E; CreateEdge edge[]; // Creates a graph with V vertices and E edges CreateGraph(int v, int e) { V = v; E = e; edge = new CreateEdge[e]; for (int i = 0; i < e; ++i) edge[i] = new CreateEdge(); } void BellmanFord(CreateGraph graph, int s) { int V = graph.V, E = graph.E; int dist[] = new int[V]; // Step 1: fill the distance array and predecessor array for (int i = 0; i < V; ++i) dist[i] = Integer.MAX_VALUE; // Mark the source vertex dist[s] = 0; // Step 2: relax edges |V| - 1 times for (int i = 1; i < V; ++i) { for (int j = 0; j < E; ++j) { // Get the edge data int u = graph.edge[j].s; int v = graph.edge[j].d; int w = graph.edge[j].w; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) dist[v] = dist[u] + w; } } // Step 3: detect negative cycle // if value changes then we have a negative cycle in the graph // and we cannot find the shortest distances for (int j = 0; j < E; ++j) { int u = graph.edge[j].s; int v = graph.edge[j].d; int w = graph.edge[j].w; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) { System.out.println("CreateGraph contains negative w cycle"); return; } } // No negative w cycle found! // Print the distance and predecessor array printSolution(dist, V); } // Print the solution void printSolution(int dist[], int V) { System.out.println("Vertex Distance from Source"); for (int i = 0; i < V - 1; ++i) System.out.println(i + "\t\t" + dist[i]); } public static void main(String[] args) { int V = 5; // Total vertices int E = 5; // Total Edges CreateGraph graph = new CreateGraph(V, E); // edge 0 --> 1 graph.edge[0].s = 0; graph.edge[0].d = 1; graph.edge[0].w = 5; // edge 0 --> 2 graph.edge[1].s = 0; graph.edge[1].d = 2; graph.edge[1].w = 4; // edge 1 --> 3 graph.edge[2].s = 1; graph.edge[2].d = 3; graph.edge[2].w = 3; // edge 2 --> 1 graph.edge[3].s = 2; graph.edge[3].d = 1; graph.edge[3].w = 6; // edge 3 --> 2 graph.edge[4].s = 3; graph.edge[4].d = 2; graph.edge[4].w = 2; graph.BellmanFord(graph, 0); // 0 is the source vertex } } ``` ``` // Bellman Ford Algorithm in C #include <stdio.h> #include <stdlib.h> #define INFINITY 99999 //struct for the edges of the graph struct Edge { int u; //start vertex of the edge int v; //end vertex of the edge int w; //weight of the edge (u,v) }; //Graph - it consists of edges struct Graph { int V; //total number of vertices in the graph int E; //total number of edges in the graph struct Edge *edge; //array of edges }; void bellmanford(struct Graph *g, int source); void display(int arr[], int size); int main(void) { //create graph struct Graph *g = (struct Graph *)malloc(sizeof(struct Graph)); g->V = 4; //total vertices g->E = 5; //total edges //array of edges for graph g->edge = (struct Edge *)malloc(g->E * sizeof(struct Edge)); //------- adding the edges of the graph /* edge(u, v) where u = start vertex of the edge (u,v) v = end vertex of the edge (u,v) w is the weight of the edge (u,v) */ //edge 0 --> 1 g->edge[0].u = 0; g->edge[0].v = 1; g->edge[0].w = 5; //edge 0 --> 2 g->edge[1].u = 0; g->edge[1].v = 2; g->edge[1].w = 4; //edge 1 --> 3 g->edge[2].u = 1; g->edge[2].v = 3; g->edge[2].w = 3; //edge 2 --> 1 g->edge[3].u = 2; g->edge[3].v = 1; g->edge[3].w = 6; //edge 3 --> 2 g->edge[4].u = 3; g->edge[4].v = 2; g->edge[4].w = 2; bellmanford(g, 0); //0 is the source vertex return 0; } void bellmanford(struct Graph *g, int source) { //variables int i, j, u, v, w; //total vertex in the graph g int tV = g->V; //total edge in the graph g int tE = g->E; //distance array //size equal to the number of vertices of the graph g int d[tV]; //predecessor array //size equal to the number of vertices of the graph g int p[tV]; //step 1: fill the distance array and predecessor array for (i = 0; i < tV; i++) { d[i] = INFINITY; p[i] = 0; } //mark the source vertex d[source] = 0; //step 2: relax edges |V| - 1 times for (i = 1; i <= tV - 1; i++) { for (j = 0; j < tE; j++) { //get the edge data u = g->edge[j].u; v = g->edge[j].v; w = g->edge[j].w; if (d[u] != INFINITY && d[v] > d[u] + w) { d[v] = d[u] + w; p[v] = u; } } } //step 3: detect negative cycle //if value changes then we have a negative cycle in the graph //and we cannot find the shortest distances for (i = 0; i < tE; i++) { u = g->edge[i].u; v = g->edge[i].v; w = g->edge[i].w; if (d[u] != INFINITY && d[v] > d[u] + w) { printf("Negative weight cycle detected!\n"); return; } } //No negative weight cycle found! //print the distance and predecessor array printf("Distance array: "); display(d, tV); printf("Predecessor array: "); display(p, tV); } void display(int arr[], int size) { int i; for (i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } ``` ``` // Bellman Ford Algorithm in C++ #include <bits/stdc++.h> // Struct for the edges of the graph struct Edge { int u; //start vertex of the edge int v; //end vertex of the edge int w; //w of the edge (u,v) }; // Graph - it consists of edges struct Graph { int V; // Total number of vertices in the graph int E; // Total number of edges in the graph struct Edge* edge; // Array of edges }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = new Graph; graph->V = V; // Total Vertices graph->E = E; // Total edges // Array of edges for graph graph->edge = new Edge[E]; return graph; } // Printing the solution void printArr(int arr[], int size) { int i; for (i = 0; i < size - 1; i++) { printf("%d ", arr[i]); } printf("\n"); } void BellmanFord(struct Graph* graph, int u) { int V = graph->V; int E = graph->E; int dist[V]; // Step 1: fill the distance array and predecessor array for (int i = 0; i < V; i++) dist[i] = INT_MAX; // Mark the source vertex dist[u] = 0; // Step 2: relax edges |V| - 1 times for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { // Get the edge data int u = graph->edge[j].u; int v = graph->edge[j].v; int w = graph->edge[j].w; if (dist[u] != INT_MAX && dist[u] + w < dist[v]) dist[v] = dist[u] + w; } } // Step 3: detect negative cycle // if value changes then we have a negative cycle in the graph // and we cannot find the shortest distances for (int i = 0; i < E; i++) { int u = graph->edge[i].u; int v = graph->edge[i].v; int w = graph->edge[i].w; if (dist[u] != INT_MAX && dist[u] + w < dist[v]) { printf("Graph contains negative w cycle"); return; } } // No negative weight cycle found! // Print the distance and predecessor array printArr(dist, V); return; } int main() { // Create a graph int V = 5; // Total vertices int E = 5; // Total edges // Array of edges for graph struct Graph* graph = createGraph(V, E); //------- adding the edges of the graph /* edge(u, v) where u = start vertex of the edge (u,v) v = end vertex of the edge (u,v) w is the weight of the edge (u,v) */ //edge 0 --> 1 graph->edge[0].u = 0; graph->edge[0].v = 1; graph->edge[0].w = 5; //edge 0 --> 2 graph->edge[1].u = 0; graph->edge[1].v = 2; graph->edge[1].w = 4; //edge 1 --> 3 graph->edge[2].u = 1; graph->edge[2].v = 3; graph->edge[2].w = 3; //edge 2 --> 1 graph->edge[3].u = 2; graph->edge[3].v = 1; graph->edge[3].w = 6; //edge 3 --> 2 graph->edge[4].u = 3; graph->edge[4].v = 2; graph->edge[4].w = 2; BellmanFord(graph, 0); //0 is the source vertex return 0; } ``` *** ## Bellman Ford's Complexity ### Time Complexity | | | |---|---| | Best Case Complexity | O(E) | | Average Case Complexity | O(VE) | | Worst Case Complexity | O(VE) | ### Space Complexity And, the space complexity is `O(V)`. *** ## Bellman Ford's Algorithm Applications 1. For calculating shortest paths in routing algorithms 2. For finding the shortest path ### Table of Contents - [Introduction](https://www.programiz.com/dsa/bellman-ford-algorithm#introduction) - [Why would one ever have edges with negative weights in real life?](https://www.programiz.com/dsa/bellman-ford-algorithm#why) - [Why do we need to be careful with negative weights?](https://www.programiz.com/dsa/bellman-ford-algorithm#negative-weights) - [How Bellman Ford's algorithm works](https://www.programiz.com/dsa/bellman-ford-algorithm#working) - [Bellman Ford Pseudocode](https://www.programiz.com/dsa/bellman-ford-algorithm#pseudocode) - [Bellman Ford vs Dijkstra](https://www.programiz.com/dsa/bellman-ford-algorithm#vs) - [Bellman Ford's Algorithm Code](https://www.programiz.com/dsa/bellman-ford-algorithm#code) [Previous Tutorial: Breadth-first Search](https://www.programiz.com/dsa/graph-bfs "Breadth-first Search") [Next Tutorial: Bubble Sort](https://www.programiz.com/dsa/bubble-sort "Bubble Sort") Share on: Did you find this article helpful? Your builder path starts here. Builders don't just know how to code, they create solutions that matter. Escape tutorial hell and ship real projects. [Try Programiz PRO](https://programiz.pro/offer/black-november-2025?utm_source=programiz.com&utm_medium=referral&utm_audience=ORGANIC-FREEMIUM&utm_campaign=offer-black-november-sale&utm_content=interests_learn_coding&utm_term=tutorial_page_footer_banner "Programiz PRO: Premium Learning Platform from Programiz") - Real-World Projects - On-Demand Learning - AI Mentor - Builder Community ### Related Tutorials [DS & Algorithms Graph Data Stucture](https://www.programiz.com/dsa/graph) [DS & Algorithms Prim's Algorithm](https://www.programiz.com/dsa/prim-algorithm) [DS & Algorithms Dijkstra's Algorithm](https://www.programiz.com/dsa/dijkstra-algorithm) [DS & Algorithms Kruskal's Algorithm](https://www.programiz.com/dsa/kruskal-algorithm) #### Free Tutorials - [Python 3 Tutorials](https://www.programiz.com/python-programming "Python 3 Tutorials") - [SQL Tutorials](https://www.programiz.com/sql "SQL Tutorials") - [R Tutorials](https://www.programiz.com/r "R Tutorials") - [HTML Tutorials](https://www.programiz.com/html "HTML Tutorials") - [CSS Tutorials](https://www.programiz.com/css "CSS Tutorials") - [JavaScript Tutorials](https://www.programiz.com/javascript "JavaScript Tutorials") - [TypeScript Tutorials](https://www.programiz.com/typescript "TypeScript Tutorials") - [Java Tutorials](https://www.programiz.com/java-programming "Java Tutorials") - [C Tutorials](https://www.programiz.com/c-programming "C Tutorials") - [C++ Tutorials](https://www.programiz.com/cpp-programming "C++ Tutorials") - [DSA Tutorials](https://www.programiz.com/dsa "Data Structures and Algorithms") - [C\# Tutorials](https://www.programiz.com/csharp-programming "C# Tutorials") - [Golang Tutorials](https://www.programiz.com/golang "Golang Tutorials") - [Kotlin Tutorials](https://www.programiz.com/kotlin-programming "Kotlin Tutorials") - [Swift Tutorials](https://www.programiz.com/swift-programming "Swift Tutorials") - [Rust Tutorials](https://www.programiz.com/rust "Rust Tutorials") - [Ruby Tutorials](https://www.programiz.com/ruby "Ruby Tutorials") #### Paid Courses - [Master Python](https://programiz.pro/learn/master-python "Master Python") - [Learn SQL](https://programiz.pro/course/learn-sql-basics "Learn SQL") - [Learn HTML](https://programiz.pro/course/learn-html "Learn HTML") - [Master JavaScript](https://programiz.pro/learn/master-javascript "Master JavaScript") - [Master C](https://programiz.pro/learn/master-c-programming "Master C") - [Master C++](https://programiz.pro/learn/master-cpp "Master C++") - [Master Java](https://programiz.pro/learn/master-java "Master Java") - [Master DSA with Python](https://programiz.pro/learn/master-dsa-with-python "Master DSA with Python") #### Online Compilers - [Python Compiler](https://www.programiz.com/python-programming/online-compiler "Python Compiler") - [R Compiler](https://www.programiz.com/r/online-compiler "R Compiler") - [SQL Editor](https://www.programiz.com/sql/online-compiler "SQL Editor") - [HTML/CSS Editor](https://www.programiz.com/html/online-compiler "HTML/CSS Editor") - [JavaScript Editor](https://www.programiz.com/javascript/online-compiler "JavaScript Editor") - [TypeScript Editor](https://www.programiz.com/typescript/online-compiler "TypeScript Editor") - [Java Compiler](https://www.programiz.com/java-programming/online-compiler "Java Compiler") - [C Compiler](https://www.programiz.com/c-programming/online-compiler "C Compiler") - [C++ Compiler](https://www.programiz.com/cpp-programming/online-compiler "C++ Compiler") - [C\# Compiler](https://www.programiz.com/csharp-programming/online-compiler "C# Compiler") - [Go Compiler](https://www.programiz.com/golang/online-compiler "Go Compiler") - [PHP Compiler](https://www.programiz.com/php/online-compiler "PHP Compiler") - [Swift Compiler](https://www.programiz.com/swift/online-compiler "Swift Compiler") - [Rust Compiler](https://www.programiz.com/rust/online-compiler "Rust Compiler") - [Ruby Compiler](https://www.programiz.com/ruby/online-compiler "Ruby Compiler") #### Mobile Apps - [Learn Python App](https://www.programiz.com/learn-python "Learn Python: Programiz") - [Learn C App](https://www.programiz.com/learn-c "Learn C Programming: Programiz") - [Learn Java App](https://www.programiz.com/learn-java "Learn Java: Programiz") - [Learn C++ App](https://www.programiz.com/learn-cpp "Learn C++: Programiz") #### Company - [Change Ad Consent]() - [Do not sell my data]() - [About](https://www.programiz.com/about-us "About us") - [Contact](https://www.programiz.com/contact "Contact us") - [Blog](https://www.programiz.com/blog "Blog") - [Youtube](https://www.youtube.com/channel/UCREFp3D_n8JfcDonlm7Mpyw "Programiz on Youtube") - [Careers](https://www.programiz.com/careers "Careers") - [Advertising](https://www.programiz.com/advertise "Advertise with us") - [Privacy Policy](https://www.programiz.com/privacy-policy "Privacy Policy") - [Terms & Conditions](https://www.programiz.com/terms-of-use "Terms & Conditions") © Parewa Labs Pvt. Ltd. All rights reserved.
Readable Markdown
It is similar to [Dijkstra's algorithm](https://www.programiz.com/dsa/dijkstra-algorithm) but it can work with graphs in which edges can have negative weights. *** ## Why would one ever have edges with negative weights in real life? Negative weight edges might seem useless at first but they can explain a lot of phenomena like cashflow, the heat released/absorbed in a chemical reaction, etc. For instance, if there are different ways to reach from one chemical A to another chemical B, each method will have sub-reactions involving both heat dissipation and absorption. If we want to find the set of reactions where minimum energy is required, then we will need to be able to factor in the heat absorption as negative weights and heat dissipation as positive weights. *** ## Why do we need to be careful with negative weights? Negative weight edges can create negative weight cycles i.e. a cycle that will reduce the total path distance by coming back to the same point. ![negative weight cycles can give an incorrect result when trying to find out the shortest path](https://cdn.programiz.com/sites/tutorial2program/files/negative-weight-cycle_1.png) Negative weight cycles can give an incorrect result when trying to find out the shortest path Shortest path algorithms like Dijkstra's Algorithm that aren't able to detect such a cycle can give an incorrect result because they can go through a negative weight cycle and reduce the path length. *** ## How Bellman Ford's algorithm works Bellman Ford algorithm works by overestimating the length of the path from the starting vertex to all other vertices. Then it iteratively relaxes those estimates by finding new paths that are shorter than the previously overestimated paths. By doing this repeatedly for all vertices, we can guarantee that the result is optimized. ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-1.png) Step-1 for Bellman Ford's algorithm ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-2.png) Step-2 for Bellman Ford's algorithm ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-3.png) Step-3 for Bellman Ford's algorithm **Note:** To relax the path, an edge(U, V), if `distance(U) + edge_weight(U,V)` \< `distance(V)`, assign `distance(V)` = `distance(U) + edge_weight(U,V)`. ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-4.png) Step-4 for Bellman Ford's algorithm ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-5.png) Step-5 for Bellman Ford's algorithm ![steps for bellman ford algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-algorithm-6.png) Step-6 for Bellman Ford's algorithm *** ## Bellman Ford Pseudocode We need to maintain the path distance of every vertex. We can store that in an array of size v, where v is the number of vertices. We also want to be able to get the shortest path, not only know the length of the shortest path. For this, we map each vertex to the vertex that last updated its path length. Once the algorithm is over, we can backtrack from the destination vertex to the source vertex to find the path. ``` function bellmanFord(G, S) for each vertex V in G distance[V] <- infinite previous[V] <- NULL distance[S] <- 0 for each vertex V in G for each edge (U,V) in G tempDistance <- distance[U] + edge_weight(U, V) if tempDistance < distance[V] distance[V] <- tempDistance previous[V] <- U for each edge (U,V) in G if distance[U] + edge_weight(U, V) < distance[V] Error: Negative Cycle Exists return distance[], previous[] ``` *** ## Bellman Ford vs Dijkstra Bellman Ford's algorithm and Dijkstra's algorithm are very similar in structure. While Dijkstra looks only to the immediate neighbors of a vertex, Bellman goes through each edge in every iteration. ![Dijkstra's vs Bellman Ford's Algorithm](https://cdn.programiz.com/sites/tutorial2program/files/bellman-ford-vs-dijkstra.jpg) Bellman Ford's Algorithm vs Dijkstra's Algorithm *** ## Python, Java and C/C++ Examples ``` # Bellman Ford Algorithm in Python class Graph: def __init__(self, vertices): self.V = vertices # Total number of vertices in the graph self.graph = [] # Array of edges # Add edges def add_edge(self, s, d, w): self.graph.append([s, d, w]) # Print the solution def print_solution(self, dist): print("Vertex Distance from Source") for i in range(self.V - 1): print("{0}\t\t{1}".format(i, dist[i])) def bellman_ford(self, src): # Step 1: fill the distance array and predecessor array dist = [float("Inf")] * self.V # Mark the source vertex dist[src] = 0 # Step 2: relax edges |V| - 1 times for _ in range(self.V - 1): for s, d, w in self.graph: if dist[s] != float("Inf") and dist[s] + w < dist[d]: dist[d] = dist[s] + w # Step 3: detect negative cycle # if value changes then we have a negative cycle in the graph # and we cannot find the shortest distances for s, d, w in self.graph: if dist[s] != float("Inf") and dist[s] + w < dist[d]: print("Graph contains negative weight cycle") return # No negative weight cycle found! # Print the distance and predecessor array self.print_solution(dist) g = Graph(5) g.add_edge(0, 1, 5) g.add_edge(0, 2, 4) g.add_edge(1, 3, 3) g.add_edge(2, 1, 6) g.add_edge(3, 2, 2) g.bellman_ford(0) ``` ``` // Bellman Ford Algorithm in Java class CreateGraph { // CreateGraph - it consists of edges class CreateEdge { int s, d, w; CreateEdge() { s = d = w = 0; } }; int V, E; CreateEdge edge[]; // Creates a graph with V vertices and E edges CreateGraph(int v, int e) { V = v; E = e; edge = new CreateEdge[e]; for (int i = 0; i < e; ++i) edge[i] = new CreateEdge(); } void BellmanFord(CreateGraph graph, int s) { int V = graph.V, E = graph.E; int dist[] = new int[V]; // Step 1: fill the distance array and predecessor array for (int i = 0; i < V; ++i) dist[i] = Integer.MAX_VALUE; // Mark the source vertex dist[s] = 0; // Step 2: relax edges |V| - 1 times for (int i = 1; i < V; ++i) { for (int j = 0; j < E; ++j) { // Get the edge data int u = graph.edge[j].s; int v = graph.edge[j].d; int w = graph.edge[j].w; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) dist[v] = dist[u] + w; } } // Step 3: detect negative cycle // if value changes then we have a negative cycle in the graph // and we cannot find the shortest distances for (int j = 0; j < E; ++j) { int u = graph.edge[j].s; int v = graph.edge[j].d; int w = graph.edge[j].w; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) { System.out.println("CreateGraph contains negative w cycle"); return; } } // No negative w cycle found! // Print the distance and predecessor array printSolution(dist, V); } // Print the solution void printSolution(int dist[], int V) { System.out.println("Vertex Distance from Source"); for (int i = 0; i < V - 1; ++i) System.out.println(i + "\t\t" + dist[i]); } public static void main(String[] args) { int V = 5; // Total vertices int E = 5; // Total Edges CreateGraph graph = new CreateGraph(V, E); // edge 0 --> 1 graph.edge[0].s = 0; graph.edge[0].d = 1; graph.edge[0].w = 5; // edge 0 --> 2 graph.edge[1].s = 0; graph.edge[1].d = 2; graph.edge[1].w = 4; // edge 1 --> 3 graph.edge[2].s = 1; graph.edge[2].d = 3; graph.edge[2].w = 3; // edge 2 --> 1 graph.edge[3].s = 2; graph.edge[3].d = 1; graph.edge[3].w = 6; // edge 3 --> 2 graph.edge[4].s = 3; graph.edge[4].d = 2; graph.edge[4].w = 2; graph.BellmanFord(graph, 0); // 0 is the source vertex } } ``` ``` // Bellman Ford Algorithm in C #include <stdio.h> #include <stdlib.h> #define INFINITY 99999 //struct for the edges of the graph struct Edge { int u; //start vertex of the edge int v; //end vertex of the edge int w; //weight of the edge (u,v) }; //Graph - it consists of edges struct Graph { int V; //total number of vertices in the graph int E; //total number of edges in the graph struct Edge *edge; //array of edges }; void bellmanford(struct Graph *g, int source); void display(int arr[], int size); int main(void) { //create graph struct Graph *g = (struct Graph *)malloc(sizeof(struct Graph)); g->V = 4; //total vertices g->E = 5; //total edges //array of edges for graph g->edge = (struct Edge *)malloc(g->E * sizeof(struct Edge)); //------- adding the edges of the graph /* edge(u, v) where u = start vertex of the edge (u,v) v = end vertex of the edge (u,v) w is the weight of the edge (u,v) */ //edge 0 --> 1 g->edge[0].u = 0; g->edge[0].v = 1; g->edge[0].w = 5; //edge 0 --> 2 g->edge[1].u = 0; g->edge[1].v = 2; g->edge[1].w = 4; //edge 1 --> 3 g->edge[2].u = 1; g->edge[2].v = 3; g->edge[2].w = 3; //edge 2 --> 1 g->edge[3].u = 2; g->edge[3].v = 1; g->edge[3].w = 6; //edge 3 --> 2 g->edge[4].u = 3; g->edge[4].v = 2; g->edge[4].w = 2; bellmanford(g, 0); //0 is the source vertex return 0; } void bellmanford(struct Graph *g, int source) { //variables int i, j, u, v, w; //total vertex in the graph g int tV = g->V; //total edge in the graph g int tE = g->E; //distance array //size equal to the number of vertices of the graph g int d[tV]; //predecessor array //size equal to the number of vertices of the graph g int p[tV]; //step 1: fill the distance array and predecessor array for (i = 0; i < tV; i++) { d[i] = INFINITY; p[i] = 0; } //mark the source vertex d[source] = 0; //step 2: relax edges |V| - 1 times for (i = 1; i <= tV - 1; i++) { for (j = 0; j < tE; j++) { //get the edge data u = g->edge[j].u; v = g->edge[j].v; w = g->edge[j].w; if (d[u] != INFINITY && d[v] > d[u] + w) { d[v] = d[u] + w; p[v] = u; } } } //step 3: detect negative cycle //if value changes then we have a negative cycle in the graph //and we cannot find the shortest distances for (i = 0; i < tE; i++) { u = g->edge[i].u; v = g->edge[i].v; w = g->edge[i].w; if (d[u] != INFINITY && d[v] > d[u] + w) { printf("Negative weight cycle detected!\n"); return; } } //No negative weight cycle found! //print the distance and predecessor array printf("Distance array: "); display(d, tV); printf("Predecessor array: "); display(p, tV); } void display(int arr[], int size) { int i; for (i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } ``` ``` // Bellman Ford Algorithm in C++ #include <bits/stdc++.h> // Struct for the edges of the graph struct Edge { int u; //start vertex of the edge int v; //end vertex of the edge int w; //w of the edge (u,v) }; // Graph - it consists of edges struct Graph { int V; // Total number of vertices in the graph int E; // Total number of edges in the graph struct Edge* edge; // Array of edges }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = new Graph; graph->V = V; // Total Vertices graph->E = E; // Total edges // Array of edges for graph graph->edge = new Edge[E]; return graph; } // Printing the solution void printArr(int arr[], int size) { int i; for (i = 0; i < size - 1; i++) { printf("%d ", arr[i]); } printf("\n"); } void BellmanFord(struct Graph* graph, int u) { int V = graph->V; int E = graph->E; int dist[V]; // Step 1: fill the distance array and predecessor array for (int i = 0; i < V; i++) dist[i] = INT_MAX; // Mark the source vertex dist[u] = 0; // Step 2: relax edges |V| - 1 times for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { // Get the edge data int u = graph->edge[j].u; int v = graph->edge[j].v; int w = graph->edge[j].w; if (dist[u] != INT_MAX && dist[u] + w < dist[v]) dist[v] = dist[u] + w; } } // Step 3: detect negative cycle // if value changes then we have a negative cycle in the graph // and we cannot find the shortest distances for (int i = 0; i < E; i++) { int u = graph->edge[i].u; int v = graph->edge[i].v; int w = graph->edge[i].w; if (dist[u] != INT_MAX && dist[u] + w < dist[v]) { printf("Graph contains negative w cycle"); return; } } // No negative weight cycle found! // Print the distance and predecessor array printArr(dist, V); return; } int main() { // Create a graph int V = 5; // Total vertices int E = 5; // Total edges // Array of edges for graph struct Graph* graph = createGraph(V, E); //------- adding the edges of the graph /* edge(u, v) where u = start vertex of the edge (u,v) v = end vertex of the edge (u,v) w is the weight of the edge (u,v) */ //edge 0 --> 1 graph->edge[0].u = 0; graph->edge[0].v = 1; graph->edge[0].w = 5; //edge 0 --> 2 graph->edge[1].u = 0; graph->edge[1].v = 2; graph->edge[1].w = 4; //edge 1 --> 3 graph->edge[2].u = 1; graph->edge[2].v = 3; graph->edge[2].w = 3; //edge 2 --> 1 graph->edge[3].u = 2; graph->edge[3].v = 1; graph->edge[3].w = 6; //edge 3 --> 2 graph->edge[4].u = 3; graph->edge[4].v = 2; graph->edge[4].w = 2; BellmanFord(graph, 0); //0 is the source vertex return 0; } ``` *** ## Bellman Ford's Complexity ### Time Complexity | | | |---|---| | Best Case Complexity | O(E) | | Average Case Complexity | O(VE) | | Worst Case Complexity | O(VE) | ### Space Complexity And, the space complexity is `O(V)`. *** ## Bellman Ford's Algorithm Applications 1. For calculating shortest paths in routing algorithms 2. For finding the shortest path
Shard35 (laksa)
Root Hash16786490165506891835
Unparsed URLcom,programiz!www,/dsa/bellman-ford-algorithm s443