Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Bellman Ford Algorithm | Distance from the Source Explained Step-by-Step
    Data Structures & Algorithms

    Bellman Ford Algorithm | Distance from the Source Explained Step-by-Step

    codeanddebugBy codeanddebug26 June 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of implmenting bellman ford algorithm
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Bellman Ford Algorithm made easy: learn how to find shortest paths (and detect negatives) with clear intuition, commented Python code, dry run, and Big-O.

    Here’s the [Problem Link] to begin with.

    Contents:
     [show]
    • 1. What does the problem ask?
    • 2. Mini example
    • 3. Why use the Bellman Ford Algorithm?
    • 4. Python code
    • 5. Step-by-step explanation
    • 6. Dry run (tiny graph)
    • 7. Complexity
    • 8. Conclusion

    1. What does the problem ask?

    Given:

    • V vertices (0 … V-1)
    • a list of directed edges [u, v, w] (w may be negative)
    • a source vertex src

    Return an array dist where dist[i] is the shortest distance from src to i.
    If the graph has a negative-weight cycle reachable from src, return [-1].


    2. Mini example

    V = 5
    edges = [
      [0,1,6], [0,2,7], [1,2,8], [1,3,5],
      [1,4,-4], [2,3,-3], [2,4,9], [3,1,-2],
      [4,3,7],  [4,0,2]
    ]
    src = 0

    Shortest distances = [0, 2, 7, 4, -2]
    (No negative cycle exists.)


    3. Why use the Bellman Ford Algorithm?

    • Handles negative weights safely.
    • Detects negative cycles.
    • Works in O(V × E) time – slower than Dijkstra but more general.

    Idea:

    1. Relax every edge V – 1 times.
      After these rounds, all shortest paths (which have at most V-1 edges) are fixed.
    2. One more scan – if any edge can still relax, a negative cycle is reachable.

    4. Python code

    class Solution:
        def bellmanFord(self, V, edges, src):
            INF = 10**8                       # a very large number
            dist = [INF for _ in range(V)]
            dist[src] = 0                     # distance to source is zero
    
            # repeat edge relaxation V-1 times
            for _ in range(V - 1):
                for u, v, w in edges:
                    if dist[u] != INF and dist[u] + w < dist[v]:
                        dist[v] = dist[u] + w
    
            # check for negative-weight cycles
            for u, v, w in edges:
                if dist[u] != INF and dist[u] + w < dist[v]:
                    return [-1]               # cycle found
    
            return dist                       # shortest distances

    5. Step-by-step explanation

    1. dist array – start with “infinity” except the source.
    2. Main loop (V-1 rounds)
      • For every edge, try to go “one step further”.
      • If going through u shortens v, store the better value.
    3. Cycle test
      • After V-1 rounds, shortest paths are done.
      • A further improvement means distance can shrink forever → negative cycle.
    4. Return
      • [-1] if a cycle exists; otherwise the dist list.

    6. Dry run (tiny graph)

    Edges
    0→1 (4), 0→2 (5), 1→2 (-2)

    RoundRelaxationsdist
    Init–[0, ∞, ∞]
    10→1 = 4, 0→2 = 5, 1→2 = 2[0, 4, 2]
    2no changes[0, 4, 2]

    Final distances: 0, 4, 2.


    7. Complexity

    MeasureValue
    TimeO(V × E)
    SpaceO(V)

    8. Conclusion

    • The Bellman Ford Algorithm is the go-to tool when edges may be negative.
    • Relax each edge for V-1 rounds, then do one extra check for cycles.
    • Simple loops, no fancy data structures – perfect for interviews dealing with tricky weights.
    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Graph Hard
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleNumber of Ways to Arrive at Destination | Leetcode 1976 | Simple Dijkstra + Path-Counting Guide in Python
    Next Article Floyd Warshall vs. Multi-Source Dijkstra | Two Ways to Solve All-Pairs Shortest Paths
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Maximum Subarray | Kadane’s Algorithm | From Brute Force to Optimal

    26 June 2025
    Data Structures & Algorithms

    Find the City With the Smallest Number of Neighbors at a Threshold Distance | Floyd Warshall vs. Dijkstra

    26 June 2025
    Data Structures & Algorithms

    Floyd Warshall vs. Multi-Source Dijkstra | Two Ways to Solve All-Pairs Shortest Paths

    26 June 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (67)
      • Beginner (30)
      • Expert (17)
      • Intermediate (20)
    • Uncategorised (1)
    Recent Posts

    Maximum Subarray | Kadane’s Algorithm | From Brute Force to Optimal

    26 June 2025

    Find the City With the Smallest Number of Neighbors at a Threshold Distance | Floyd Warshall vs. Dijkstra

    26 June 2025

    Floyd Warshall vs. Multi-Source Dijkstra | Two Ways to Solve All-Pairs Shortest Paths

    26 June 2025

    Bellman Ford Algorithm | Distance from the Source Explained Step-by-Step

    26 June 2025

    Number of Ways to Arrive at Destination | Leetcode 1976 | Simple Dijkstra + Path-Counting Guide in Python

    26 June 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.