DATA STRUCTURES PROGRAM • GRAPHS

Find Shortest Paths with Bellman-Ford

Learn how to find shortest paths with bellman-ford using a clear C program.

AdvancedBellman-FordNegative edgesRelaxation

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0 -1 2 -2 1

COMPLETE C PROGRAM

Complete C implementation

dsa-bellman-ford-shortest-path.c
Open in compiler
#include <stdio.h>
#include <limits.h>

struct Edge { int from; int to; int weight; };

int main(void)
{
    struct Edge edges[] = {
        {0,1,-1},{0,2,4},{1,2,3},{1,3,2},{1,4,2},{3,2,5},{3,1,1},{4,3,-3}
    };
    int distance[5] = {0, INT_MAX, INT_MAX, INT_MAX, INT_MAX};
    for (int pass = 1; pass < 5; pass++)
        for (int index = 0; index < 8; index++) {
            int from = edges[index].from, to = edges[index].to, weight = edges[index].weight;
            if (distance[from] != INT_MAX && distance[from] + weight < distance[to])
                distance[to] = distance[from] + weight;
        }
    for (int vertex = 0; vertex < 5; vertex++) printf("%d ", distance[vertex]);
    putchar('\n');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0 -1 2 -2 1
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Relax every edge V-1 times so shortest paths with negative edges can propagate.
  3. Display the computed result.

Relax every edge V-1 times so shortest paths with negative edges can propagate.

EFFICIENCY

Time and space complexity

Time complexity

O(VE)

Auxiliary space

O(V)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.