πŸ•·οΈ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 103 (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
8 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.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/
Last Crawled2026-04-06 07:51:48 (8 hours ago)
First Indexed2025-06-13 23:28:47 (9 months ago)
HTTP Status Code200
Meta TitleBellman–Ford Algorithm - GeeksforGeeks
Meta DescriptionYour All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more., Your All-in-One Learning Portal. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Meta Canonicalnull
Boilerpipe Text
Last Updated : 23 Jul, 2025 Given a weighted graph with V vertices and E edges, along with a source vertex src , the task is to compute the shortest distances from the source to all other vertices. If a vertex is unreachable from the source, its distance should be marked as 10 8 . In the presence of a negative weight cycle, return -1 to signify that shortest path calculations are not feasible. Examples: Input : V = 5, edges = [[0, 1, 5], [1, 2, 1], [1, 3, 2], [2, 4, 1], [4, 3, -1]], src = 0 Output : [0, 5, 6, 6, 7] Explanation: Shortest Paths: For 0 to 1 minimum distance will be 5. By following path 0 β†’ 1 For 0 to 2 minimum distance will be 6. By following path 0 β†’ 1 β†’ 2 For 0 to 3 minimum distance will be 6. By following path 0 β†’ 1 β†’ 2 β†’ 4 β†’ 3 For 0 to 4 minimum distance will be 7. By following path 0 β†’ 1 β†’ 2 β†’ 4 Input : V = 4, edges = [[0, 1, 4], [1, 2, -6], [2, 3, 5], [3, 1, -2]], src = 0 Output : [-1] Explanation: The graph contains a negative weight cycle formed by the path 1 β†’ 2 β†’ 3 β†’ 1 , where the total weight of the cycle is negative. Try it on GfG Practice Table of Content Bellman-Ford Algorithm - O(V*E) Time and O(V) Space Negative weight cycle: Limitation of Dijkstra's Algorithm: Principle of Relaxation of Edges Why Relaxing Edges (V - 1) times gives us Single Source Shortest Path? Detection of a Negative Weight Cycle Problems based on Shortest Path Approach: Bellman-Ford Algorithm - O(V*E) Time and O(V) Space Negative weight cycle: A negative weight cycle is a cycle in a graph, whose sum of edge weights is negative. If you traverse the cycle, the total weight accumulated would be less than zero. In the presence of negative weight cycle in the graph, the shortest path doesn't exist because with each traversal of the cycle shortest path keeps decreasing . Limitation of Dijkstra's Algorithm: Since, we need to find the single source shortest path , we might initially think of using Dijkstra's algorithm . However, Dijkstra is not suitable when the graph consists of negative edges . The reason is, it doesn't revisit those nodes which have already been marked as visited. If a shorter path exists through a longer route with negative edges, Dijkstra's algorithm will fail to handle it. Principle of Relaxation of Edges Relaxation means updating the shortest distance to a node if a shorter path is found through another node. For an edge (u, v) with weight w : If going through u gives a shorter path to v from the source node (i.e., distance[v] > distance[u] + w ), we update the distance[v] as distance[u] + w. In the bellman-ford algorithm, this process is repeated (V - 1) times for all the edges. Why Relaxing Edges (V - 1) times gives us Single Source Shortest Path? A shortest path between two vertices can have at most (V - 1) edges. It is not possible to have a simple path with more than (V - 1) edges (otherwise it would form a cycle). Therefore, repeating the relaxation process (V - 1) times ensures that all possible paths between source and any other node have been covered. Assuming node 0 as the source vertex, let's see how we can relax the edges to find the shortest paths: In the first relaxation , since the shortest paths for vertices 1 and 2 are unknown (infinite, i.e., 10 8 ), the shortest paths for vertices 2 and 3 will also remain infinite (10 8 ) . And, for vertex 1, the distance will be updated to 4, as dist[0] + 4 < dist[1] (i.e., 0 + 4 < 10 8 ). In the second relaxation , the shortest path for vertex 2 is still infinite (e.g. 10 8 ), which means the shortest path for vertex 3 will also remain infinite. For vertex 2, the distance can be updated to 3, as dist[1] + (-1) = 3. In the third relaxation , the shortest path for vertex 3 will be updated to 5, as dist[2] + 2 = 5. So, in above example, dist[1] is updated in 1st relaxation , dist[2] is updated in second relaxation , so the dist for the last node (V - 1), will be updated in (V - 1) th relaxation . Detection of a Negative Weight Cycle As we have discussed earlier that, we need (V - 1) relaxations of all the edges to achieve single source shortest path. If one additional relaxation (Vth) for any edge is possible, it indicates that some edges with overall negative weight has been traversed once more. This indicates the presence of a negative weight cycle in the graph. Bellman-Ford is a single source shortest path algorithm. It effectively works in the cases of negative edges and is able to detect negative cycles as well. It works on the principle of relaxation of the edges . Illustration: Previous Pause Next 4 / 6 C++ Java Python C# JavaScript Output 0 5 6 6 7 Problems based on Shortest Path Shortest Path in Directed Acyclic Graph Shortest path with one curved edge in an undirected Graph Minimum Cost Path Path with smallest difference between consecutive cells Print negative weight cycle in a Directed Graph 1st to Kth shortest path lengths in given Graph Shortest path in a Binary Maze Minimum steps to reach target by a Knight Number of ways to reach at destination in shortest time Snake and Ladder Problem Word Ladder
Markdown
[![geeksforgeeks](https://media.geeksforgeeks.org/gfg-gg-logo.svg)](https://www.geeksforgeeks.org/) ![search icon](https://media.geeksforgeeks.org/auth-dashboard-uploads/Property=Light---Default.svg) - Sign In - [Courses]() - [Tutorials]() - [Interview Prep]() - [DSA Tutorial](https://www.geeksforgeeks.org/dsa/dsa-tutorial-learn-data-structures-and-algorithms/) - [Interview Questions](https://www.geeksforgeeks.org/dsa/top-100-data-structure-and-algorithms-dsa-interview-questions-topic-wise/) - [Quizzes](https://www.geeksforgeeks.org/dsa/data-structures-and-algorithms-online-quiz/) - [Must Do](https://www.geeksforgeeks.org/dsa/must-do-coding-questions-for-companies-like-amazon-microsoft-adobe/) - [Advanced DSA](https://www.geeksforgeeks.org/dsa/advanced-data-structures/) - [System Design](https://www.geeksforgeeks.org/system-design/system-design-tutorial/) - [Aptitude](https://www.geeksforgeeks.org/aptitude/aptitude-questions-and-answers/) - [Puzzles](https://www.geeksforgeeks.org/aptitude/puzzles/) - [Interview Corner](https://www.geeksforgeeks.org/interview-prep/interview-corner/) - [DSA Python](https://www.geeksforgeeks.org/dsa/python-data-structures-and-algorithms/) # Bellman–Ford Algorithm Last Updated : 23 Jul, 2025 Given a weighted graph with ****V**** vertices and ****E**** edges, along with a source vertex**`src`**, the task is to compute the shortest distances from the source to all other vertices. If a vertex is unreachable from the source, its distance should be marked as ****10********8****. In the presence of a negative weight cycle, ****return -1**** to signify that shortest path calculations are not feasible. ****Examples:**** > ****Input****: V = 5, edges = \[\[0, 1, 5\], \[1, 2, 1\], \[1, 3, 2\], \[2, 4, 1\], \[4, 3, -1\]\], src = 0 > > ![bellman\_ford\_input\_images](https://media.geeksforgeeks.org/wp-content/uploads/20241018163210610023/bellman_ford_input_images.webp) > > ****Output****: \[0, 5, 6, 6, 7\] > ****Explanation:**** Shortest Paths: > For 0 to 1 minimum distance will be 5. By following path 0 ****β†’**** 1 > For 0 to 2 minimum distance will be 6. By following path 0 ****β†’**** 1 ****β†’**** 2 > For 0 to 3 minimum distance will be 6. By following path 0 ****β†’**** 1 ****β†’**** 2 ****β†’**** 4 ****β†’**** 3 > For 0 to 4 minimum distance will be 7. By following path 0 ****β†’**** 1 ****β†’**** 2 ****β†’**** 4 > > ****Input****: V = 4, edges = \[\[0, 1, 4\], \[1, 2, -6\], \[2, 3, 5\], \[3, 1, -2\]\], src = 0 > > ![input-2](https://media.geeksforgeeks.org/wp-content/uploads/20241016175549040804/input-2.webp) > > ****Output****: \[-1\] > ****Explanation:**** The graph contains a negative weight cycle formed by the path ****1 β†’ 2 β†’ 3 β†’ 1****, where the total weight of the cycle is negative. [Try it on GfG Practice ![redirect icon](https://media.geeksforgeeks.org/auth-dashboard-uploads/Group-arrow.svg)](https://www.geeksforgeeks.org/problems/distance-from-the-source-bellman-ford-algorithm/1) Table of Content - [Bellman-Ford Algorithm - O(V\*E) Time and O(V) Space](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#bellmanford-algorithm-ove-time-and-ov-space) - [Negative weight cycle:](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#negative-weight-cycle) - [Limitation of Dijkstra's Algorithm:](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#limitation-of-dijkstras-algorithm) - [Principle of Relaxation of Edges](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#principle-of-relaxation-of-edges) - [Why Relaxing Edges (V - 1) times gives us Single Source Shortest Path?](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#why-relaxing-edges-v-1-times-gives-us-single-source-shortest-path) - [Detection of a Negative Weight Cycle](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#detection-of-a-negative-weight-cycle) - [Problems based on Shortest Path](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#problems-based-on-shortest-path) ### Approach: Bellman-Ford Algorithm - O(V\*E) Time and O(V) Space ### Negative weight cycle: A negative weight cycle is a cycle in a graph, whose sum of edge weights is negative. If you traverse the cycle, the total weight accumulated would be less than zero. ![BellmanFord-Algorithm-eXAMPLE](https://media.geeksforgeeks.org/wp-content/uploads/20250411172807132937/BellmanFord-Algorithm-eXAMPLE.webp) In the presence of negative weight cycle in the graph, the shortest path ****doesn't exist**** because with each traversal of the cycle shortest path keeps ****decreasing****. ### Limitation of Dijkstra's Algorithm: Since, we need to find the ****single source shortest path****, we might initially think of using [Dijkstra's algorithm](https://www.geeksforgeeks.org/dsa/introduction-to-dijkstras-shortest-path-algorithm/). However, Dijkstra is not suitable when the graph consists of ****negative edges****. The reason is, it ****doesn't revisit**** those nodes which have already been marked as visited. If a shorter path exists through a longer route with negative edges, Dijkstra's algorithm will fail to handle it. ### Principle of Relaxation of Edges - Relaxation means ****updating**** the shortest distance to a node if a shorter path is found through another node. For an edge ****(u, v)**** with weight ****w****: - If going through u gives a shorter path to v from the source node (i.e., ****distance\[v\] \> distance\[u\] + w****), we update the distance\[v\] as distance\[u\] + w. - In the bellman-ford algorithm, this process is repeated ****(V - 1)**** times for all the edges. ### ****Why Relaxing Edges (V - 1) times gives us Single Source Shortest Path?**** A shortest path between two vertices can have at most ****(V - 1)**** edges. It is not possible to have a simple path with more than (V - 1) edges (otherwise it would form a cycle). Therefore, repeating the relaxation process (V - 1) times ensures that all possible paths between source and any other node have been covered. Assuming node ****0**** as the ****source**** vertex, let's see how we can relax the edges to find the shortest paths: ![baleman-fort](https://media.geeksforgeeks.org/wp-content/uploads/20241016175632718977/baleman-fort.webp) - In the ****first relaxation****, since the shortest paths for vertices 1 and 2 are unknown (infinite, i.e., 108), the shortest paths for vertices 2 and 3 will also remain infinite (108)``. And, for vertex 1, the distance will be updated to 4, as `dist[0] + 4 < dist[1]` (i.e., `0 + 4 <`108). - In the ****second relaxation****, the shortest path for vertex 2 is still infinite (e.g. 108), which means the shortest path for vertex 3 will also remain infinite. For vertex 2, the distance can be updated to 3, as dist\[1\] + (-1) = 3. - In the ****third relaxation****, the shortest path for vertex 3 will be updated to 5, as dist\[2\] + 2 = 5. So, in above example, ****dist\[1\]**** is updated in ****1st relaxation****, ****dist\[2\]**** is updated in ****second relaxation****, so the dist for the last node (V - 1), will be updated in ****(V - 1) th relaxation****. ### Detection of a Negative Weight Cycle - As we have discussed earlier that, we need (V - 1) relaxations of all the edges to achieve single source shortest path. If one ****additional relaxation**** (Vth) for any edge is possible, it indicates that some edges with overall negative weight has been traversed once more. This indicates the presence of a ****negative weight cycle**** in the graph. > ****Bellman-Ford**** is a ****single source**** shortest path algorithm. It effectively works in the cases of negative edges and is able to detect negative cycles as well. It works on the principle of ****relaxation of the edges****. ****Illustration:**** ![BellmanFord-Algorithm-1.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp)![BellmanFord-Algorithm-1.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp) ![BellmanFord-Algorithm-2.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172808932708/BellmanFord-Algorithm-2.webp)![BellmanFord-Algorithm-2.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172808932708/BellmanFord-Algorithm-2.webp) ![BellmanFord-Algorithm-3.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172808335336/BellmanFord-Algorithm-3.webp)![BellmanFord-Algorithm-3.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172808335336/BellmanFord-Algorithm-3.webp) ![BellmanFord-Algorithm-4.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172807990934/BellmanFord-Algorithm-4.webp)![BellmanFord-Algorithm-4.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172807990934/BellmanFord-Algorithm-4.webp) ![BellmanFord-Algorithm-5.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp)![BellmanFord-Algorithm-5.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp) ![BellmanFord-Algorithm-6.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp)![BellmanFord-Algorithm-6.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp) 4 / 6 C++ `` ``` #include <iostream> ``` ``` #include <vector> ``` ``` using namespace std; ``` ``` ​ ``` ``` vector<int> bellmanFord(int V, vector<vector<int>>& edges, int src) { ``` ``` ``` ``` // Initially distance from source to all ``` ``` // other vertices is not known(Infinite). ``` ``` vector<int> dist(V, 1e8); ``` ``` dist[src] = 0; ``` ``` ``` ``` // Relaxation of all the edges V times, not (V - 1) as we ``` ``` // need one additional relaxation to detect negative cycle ``` ``` for (int i = 0; i < V; i++) { ``` ``` ``` ``` for (vector<int> edge : edges) { ``` ``` int u = edge[0]; ``` ``` int v = edge[1]; ``` ``` int wt = edge[2]; ``` ``` if (dist[u] != 1e8 && dist[u] + wt < dist[v]) { ``` ``` ``` ``` // If this is the Vth relaxation, then there is ``` ``` // a negative cycle ``` ``` if(i == V - 1) ``` ``` return {-1}; ``` ``` ``` ``` // Update shortest distance to node v ``` ``` dist[v] = dist[u] + wt; ``` ``` } ``` ``` } ``` ``` } ``` ``` ​ ``` ``` return dist; ``` ``` } ``` ``` ​ ``` ``` int main() { ``` ``` ``` ``` // Number of vertices in the graph ``` ``` int V = 5; ``` ``` ​ ``` ``` // Edge list representation: {source, destination, weight} ``` ``` vector<vector<int>> edges = { ``` ``` {1, 3, 2}, ``` ``` {4, 3, -1}, ``` ``` {2, 4, 1}, ``` ``` {1, 2, 1}, ``` ``` {0, 1, 5} ``` ``` }; ``` ``` ​ ``` ``` // Define the source vertex ``` ``` int src = 0; ``` ``` ​ ``` ``` // Run Bellman-Ford algorithm to get shortest paths from src ``` ``` vector<int> ans = bellmanFord(V, edges, src); ``` ``` ​ ``` ``` // Output the shortest distances from src to all vertices ``` ``` for (int dist : ans) ``` ``` cout << dist << " "; ``` ``` ​ ``` ``` return 0; ``` ``` } ``` Java `` ``` // Relaxation of all the edges V times, not (V - 1) as we ``` Python `` ``` edges = [[1, 3, 2], [4, 3, -1], [2, 4, 1], [1, 2, 1], [0, 1, 5]] ``` C\# `` ``` // If this is the V-th iteration and relaxation is still ``` JavaScript `` ``` // If this is the Vth relaxation, then there is ``` **Output** ``` 0 5 6 6 7 ``` ### Problems based on Shortest Path - [Shortest Path in Directed Acyclic Graph](https://www.geeksforgeeks.org/dsa/shortest-path-for-directed-acyclic-graphs/) - [Shortest path with one curved edge in an undirected Graph](https://www.geeksforgeeks.org/dsa/shortest-path-with-one-curved-edge-in-an-undirected-graph/) - [Minimum Cost Path](https://www.geeksforgeeks.org/dsa/minimum-cost-path-left-right-bottom-moves-allowed/) - [Path with smallest difference between consecutive cells](https://www.geeksforgeeks.org/dsa/path-with-smallest-difference-between-consecutive-cells-path-with-minimum-effort/) - [Print negative weight cycle in a Directed Graph](https://www.geeksforgeeks.org/dsa/print-negative-weight-cycle-in-a-directed-graph/) - [1st to Kth shortest path lengths in given Graph](https://www.geeksforgeeks.org/dsa/1st-to-kth-shortest-path-lengths-from-node-1-to-n-in-given-graph/) - [Shortest path in a Binary Maze](https://www.geeksforgeeks.org/dsa/shortest-path-in-a-binary-maze/) - [Minimum steps to reach target by a Knight](https://www.geeksforgeeks.org/dsa/minimum-steps-reach-target-knight/) - [Number of ways to reach at destination in shortest time](https://www.geeksforgeeks.org/dsa/number-of-ways-to-reach-at-destination-in-shortest-time/) - [Snake and Ladder Problem](https://www.geeksforgeeks.org/dsa/snake-ladder-problem-2/) - [Word Ladder](https://www.geeksforgeeks.org/dsa/word-ladder-length-of-shortest-chain-to-reach-a-target-word/) Comment [K](https://www.geeksforgeeks.org/user/kartik/) [kartik](https://www.geeksforgeeks.org/user/kartik/) 259 Article Tags: Article Tags: [Graph](https://www.geeksforgeeks.org/category/dsa/data-structures/graph/) [Dynamic Programming](https://www.geeksforgeeks.org/category/dsa/algorithm/dynamic-programming/) [DSA](https://www.geeksforgeeks.org/category/dsa/) [Shortest Path](https://www.geeksforgeeks.org/tag/shortest-path/) ### Explore [![GeeksforGeeks](https://media.geeksforgeeks.org/auth-dashboard-uploads/gfgFooterLogo.png)](https://www.geeksforgeeks.org/) ![location](https://media.geeksforgeeks.org/img-practice/Location-1685004904.svg) Corporate & Communications Address: A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305) ![location](https://media.geeksforgeeks.org/img-practice/Location-1685004904.svg) Registered Address: K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305 [![GFG App on Play Store](https://media.geeksforgeeks.org/auth-dashboard-uploads/googleplay-%281%29.png)](https://geeksforgeeksapp.page.link/gfg-app)[![GFG App on App Store](https://media.geeksforgeeks.org/auth-dashboard-uploads/appstore-%281%29.png)](https://geeksforgeeksapp.page.link/gfg-app) - Company - [About Us](https://www.geeksforgeeks.org/about/) - [Legal](https://www.geeksforgeeks.org/legal/) - [Privacy Policy](https://www.geeksforgeeks.org/legal/privacy-policy/) - [Contact Us](https://www.geeksforgeeks.org/about/contact-us/) - [Advertise with us](https://www.geeksforgeeks.org/advertise-with-us/) - [GFG Corporate Solution](https://www.geeksforgeeks.org/gfg-corporate-solution/) - [Campus Training Program](https://www.geeksforgeeks.org/campus-training-program/) - Explore - [POTD](https://www.geeksforgeeks.org/problem-of-the-day) - [Job-A-Thon](https://practice.geeksforgeeks.org/events/rec/job-a-thon/) - [Blogs](https://www.geeksforgeeks.org/category/blogs/?type=recent) - [Nation Skill Up](https://www.geeksforgeeks.org/nation-skill-up/) - Tutorials - [Programming Languages](https://www.geeksforgeeks.org/computer-science-fundamentals/programming-language-tutorials/) - [DSA](https://www.geeksforgeeks.org/dsa/dsa-tutorial-learn-data-structures-and-algorithms/) - [Web Technology](https://www.geeksforgeeks.org/web-tech/web-technology/) - [AI, ML & Data Science](https://www.geeksforgeeks.org/machine-learning/ai-ml-and-data-science-tutorial-learn-ai-ml-and-data-science/) - [DevOps](https://www.geeksforgeeks.org/devops/devops-tutorial/) - [CS Core Subjects](https://www.geeksforgeeks.org/gate/gate-exam-tutorial/) - [Interview Preparation](https://www.geeksforgeeks.org/aptitude/interview-corner/) - [Software and Tools](https://www.geeksforgeeks.org/websites-apps/software-and-tools-a-to-z-list/) - Courses - [ML and Data Science](https://www.geeksforgeeks.org/courses/category/machine-learning-data-science) - [DSA and Placements](https://www.geeksforgeeks.org/courses/category/dsa-placements) - [Web Development](https://www.geeksforgeeks.org/courses/category/development-testing) - [Programming Languages](https://www.geeksforgeeks.org/courses/category/programming-languages) - [DevOps & Cloud](https://www.geeksforgeeks.org/courses/category/cloud-devops) - [GATE](https://www.geeksforgeeks.org/courses/category/gate) - [Trending Technologies](https://www.geeksforgeeks.org/courses/category/trending-technologies/) - Videos - [DSA](https://www.geeksforgeeks.org/videos/category/sde-sheet/) - [Python](https://www.geeksforgeeks.org/videos/category/python/) - [Java](https://www.geeksforgeeks.org/videos/category/java-w6y5f4/) - [C++](https://www.geeksforgeeks.org/videos/category/c/) - [Web Development](https://www.geeksforgeeks.org/videos/category/web-development/) - [Data Science](https://www.geeksforgeeks.org/videos/category/data-science/) - [CS Subjects](https://www.geeksforgeeks.org/videos/category/cs-subjects/) - Preparation Corner - [Interview Corner](https://www.geeksforgeeks.org/interview-prep/interview-corner/) - [Aptitude](https://www.geeksforgeeks.org/aptitude/aptitude-questions-and-answers/) - [Puzzles](https://www.geeksforgeeks.org/aptitude/puzzles/) - [GfG 160](https://www.geeksforgeeks.org/courses/gfg-160-series) - [System Design](https://www.geeksforgeeks.org/system-design/system-design-tutorial/) [@GeeksforGeeks, Sanchhaya Education Private Limited](https://www.geeksforgeeks.org/), [All rights reserved](https://www.geeksforgeeks.org/copyright-information/) ![]()
Readable Markdown
Last Updated : 23 Jul, 2025 Given a weighted graph with ****V**** vertices and ****E**** edges, along with a source vertex**`src`**, the task is to compute the shortest distances from the source to all other vertices. If a vertex is unreachable from the source, its distance should be marked as ****10********8****. In the presence of a negative weight cycle, ****return -1**** to signify that shortest path calculations are not feasible. ****Examples:**** > ****Input****: V = 5, edges = \[\[0, 1, 5\], \[1, 2, 1\], \[1, 3, 2\], \[2, 4, 1\], \[4, 3, -1\]\], src = 0 > > ![bellman\_ford\_input\_images](https://media.geeksforgeeks.org/wp-content/uploads/20241018163210610023/bellman_ford_input_images.webp) > > ****Output****: \[0, 5, 6, 6, 7\] > ****Explanation:**** Shortest Paths: > For 0 to 1 minimum distance will be 5. By following path 0 ****β†’**** 1 > For 0 to 2 minimum distance will be 6. By following path 0 ****β†’**** 1 ****β†’**** 2 > For 0 to 3 minimum distance will be 6. By following path 0 ****β†’**** 1 ****β†’**** 2 ****β†’**** 4 ****β†’**** 3 > For 0 to 4 minimum distance will be 7. By following path 0 ****β†’**** 1 ****β†’**** 2 ****β†’**** 4 > > ****Input****: V = 4, edges = \[\[0, 1, 4\], \[1, 2, -6\], \[2, 3, 5\], \[3, 1, -2\]\], src = 0 > > ![input-2](https://media.geeksforgeeks.org/wp-content/uploads/20241016175549040804/input-2.webp) > > ****Output****: \[-1\] > ****Explanation:**** The graph contains a negative weight cycle formed by the path ****1 β†’ 2 β†’ 3 β†’ 1****, where the total weight of the cycle is negative. [Try it on GfG Practice ![redirect icon](https://media.geeksforgeeks.org/auth-dashboard-uploads/Group-arrow.svg)](https://www.geeksforgeeks.org/problems/distance-from-the-source-bellman-ford-algorithm/1) Table of Content - [Bellman-Ford Algorithm - O(V\*E) Time and O(V) Space](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#bellmanford-algorithm-ove-time-and-ov-space) - [Negative weight cycle:](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#negative-weight-cycle) - [Limitation of Dijkstra's Algorithm:](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#limitation-of-dijkstras-algorithm) - [Principle of Relaxation of Edges](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#principle-of-relaxation-of-edges) - [Why Relaxing Edges (V - 1) times gives us Single Source Shortest Path?](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#why-relaxing-edges-v-1-times-gives-us-single-source-shortest-path) - [Detection of a Negative Weight Cycle](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#detection-of-a-negative-weight-cycle) - [Problems based on Shortest Path](https://www.geeksforgeeks.org/dsa/bellman-ford-algorithm-dp-23/#problems-based-on-shortest-path) ### Approach: Bellman-Ford Algorithm - O(V\*E) Time and O(V) Space ### Negative weight cycle: A negative weight cycle is a cycle in a graph, whose sum of edge weights is negative. If you traverse the cycle, the total weight accumulated would be less than zero. ![BellmanFord-Algorithm-eXAMPLE](https://media.geeksforgeeks.org/wp-content/uploads/20250411172807132937/BellmanFord-Algorithm-eXAMPLE.webp) In the presence of negative weight cycle in the graph, the shortest path ****doesn't exist**** because with each traversal of the cycle shortest path keeps ****decreasing****. ### Limitation of Dijkstra's Algorithm: Since, we need to find the ****single source shortest path****, we might initially think of using [Dijkstra's algorithm](https://www.geeksforgeeks.org/dsa/introduction-to-dijkstras-shortest-path-algorithm/). However, Dijkstra is not suitable when the graph consists of ****negative edges****. The reason is, it ****doesn't revisit**** those nodes which have already been marked as visited. If a shorter path exists through a longer route with negative edges, Dijkstra's algorithm will fail to handle it. ### Principle of Relaxation of Edges - Relaxation means ****updating**** the shortest distance to a node if a shorter path is found through another node. For an edge ****(u, v)**** with weight ****w****: - If going through u gives a shorter path to v from the source node (i.e., ****distance\[v\] \> distance\[u\] + w****), we update the distance\[v\] as distance\[u\] + w. - In the bellman-ford algorithm, this process is repeated ****(V - 1)**** times for all the edges. ### ****Why Relaxing Edges (V - 1) times gives us Single Source Shortest Path?**** A shortest path between two vertices can have at most ****(V - 1)**** edges. It is not possible to have a simple path with more than (V - 1) edges (otherwise it would form a cycle). Therefore, repeating the relaxation process (V - 1) times ensures that all possible paths between source and any other node have been covered. Assuming node ****0**** as the ****source**** vertex, let's see how we can relax the edges to find the shortest paths: ![baleman-fort](https://media.geeksforgeeks.org/wp-content/uploads/20241016175632718977/baleman-fort.webp) - In the ****first relaxation****, since the shortest paths for vertices 1 and 2 are unknown (infinite, i.e., 108), the shortest paths for vertices 2 and 3 will also remain infinite (108)``. And, for vertex 1, the distance will be updated to 4, as `dist[0] + 4 < dist[1]` (i.e., `0 + 4 <`108). - In the ****second relaxation****, the shortest path for vertex 2 is still infinite (e.g. 108), which means the shortest path for vertex 3 will also remain infinite. For vertex 2, the distance can be updated to 3, as dist\[1\] + (-1) = 3. - In the ****third relaxation****, the shortest path for vertex 3 will be updated to 5, as dist\[2\] + 2 = 5. So, in above example, ****dist\[1\]**** is updated in ****1st relaxation****, ****dist\[2\]**** is updated in ****second relaxation****, so the dist for the last node (V - 1), will be updated in ****(V - 1) th relaxation****. ### Detection of a Negative Weight Cycle - As we have discussed earlier that, we need (V - 1) relaxations of all the edges to achieve single source shortest path. If one ****additional relaxation**** (Vth) for any edge is possible, it indicates that some edges with overall negative weight has been traversed once more. This indicates the presence of a ****negative weight cycle**** in the graph. > ****Bellman-Ford**** is a ****single source**** shortest path algorithm. It effectively works in the cases of negative edges and is able to detect negative cycles as well. It works on the principle of ****relaxation of the edges****. ****Illustration:**** ![BellmanFord-Algorithm-1.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp)![BellmanFord-Algorithm-1.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp) ![BellmanFord-Algorithm-2.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172808932708/BellmanFord-Algorithm-2.webp)![BellmanFord-Algorithm-2.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172808932708/BellmanFord-Algorithm-2.webp) ![BellmanFord-Algorithm-3.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172808335336/BellmanFord-Algorithm-3.webp)![BellmanFord-Algorithm-3.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172808335336/BellmanFord-Algorithm-3.webp) ![BellmanFord-Algorithm-4.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172807990934/BellmanFord-Algorithm-4.webp)![BellmanFord-Algorithm-4.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172807990934/BellmanFord-Algorithm-4.webp) ![BellmanFord-Algorithm-5.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp)![BellmanFord-Algorithm-5.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp) ![BellmanFord-Algorithm-6.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp)![BellmanFord-Algorithm-6.webp](https://media.geeksforgeeks.org/wp-content/uploads/20250411172809312969/BellmanFord-Algorithm-1.webp) 4 / 6 C++ Java Python C\# JavaScript **Output** ``` 0 5 6 6 7 ``` ### Problems based on Shortest Path - [Shortest Path in Directed Acyclic Graph](https://www.geeksforgeeks.org/dsa/shortest-path-for-directed-acyclic-graphs/) - [Shortest path with one curved edge in an undirected Graph](https://www.geeksforgeeks.org/dsa/shortest-path-with-one-curved-edge-in-an-undirected-graph/) - [Minimum Cost Path](https://www.geeksforgeeks.org/dsa/minimum-cost-path-left-right-bottom-moves-allowed/) - [Path with smallest difference between consecutive cells](https://www.geeksforgeeks.org/dsa/path-with-smallest-difference-between-consecutive-cells-path-with-minimum-effort/) - [Print negative weight cycle in a Directed Graph](https://www.geeksforgeeks.org/dsa/print-negative-weight-cycle-in-a-directed-graph/) - [1st to Kth shortest path lengths in given Graph](https://www.geeksforgeeks.org/dsa/1st-to-kth-shortest-path-lengths-from-node-1-to-n-in-given-graph/) - [Shortest path in a Binary Maze](https://www.geeksforgeeks.org/dsa/shortest-path-in-a-binary-maze/) - [Minimum steps to reach target by a Knight](https://www.geeksforgeeks.org/dsa/minimum-steps-reach-target-knight/) - [Number of ways to reach at destination in shortest time](https://www.geeksforgeeks.org/dsa/number-of-ways-to-reach-at-destination-in-shortest-time/) - [Snake and Ladder Problem](https://www.geeksforgeeks.org/dsa/snake-ladder-problem-2/) - [Word Ladder](https://www.geeksforgeeks.org/dsa/word-ladder-length-of-shortest-chain-to-reach-a-target-word/)
Shard103 (laksa)
Root Hash12046344915360636903
Unparsed URLorg,geeksforgeeks!www,/dsa/bellman-ford-algorithm-dp-23/ s443