AlgoLab
AlgorithmsCompare
AlgoLab
AlgorithmsCompareGitHub

© 2026 AlgoLab. Open source.

AlgorithmsGraphsBellman-Ford
Graphsintermediateshortest-pathnegative-weightsdynamic-programming

Bellman-Ford

Bellman-Ford computes shortest paths from a single source in a weighted graph, including graphs with negative-weight edges. It relaxes all edges V-1 times. If any distance can still be reduced after V-1 iterations, a negative cycle exists. It is slower than Dijkstra but handles negative weights.

Complexity

Best
O(VE)
Average
O(VE)
Worst
O(VE)
Space
O(V)

Visualizer

Implementation

vector<int> bellmanFord(int n, vector<tuple<int,int,int>>& edges, int src) {
    vector<int> dist(n, INT_MAX);
    dist[src]=0;
    for (int i=0;i<n-1;i++)
        for (auto [u,v,w]:edges)
            if (dist[u]!=INT_MAX && dist[u]+w<dist[v]) dist[v]=dist[u]+w;
    for (auto [u,v,w]:edges)
        if (dist[u]!=INT_MAX && dist[u]+w<dist[v]) return {}; // negative cycle
    return dist;
}

How It Works

1.V-1 Iterations

A shortest path in a graph with V vertices has at most V-1 edges. So relaxing all edges V-1 times guarantees every shortest path is found, even through intermediate nodes.

2.Negative Cycle Detection

After V-1 iterations, do one more pass. If any edge can still be relaxed, a negative cycle exists (reachable from source). The algorithm reports this correctly.

3.vs Dijkstra

Bellman-Ford is O(VE) vs Dijkstra O((V+E) log V). Dijkstra is faster but requires non-negative weights. Bellman-Ford handles negative weights and detects negative cycles.

Related Algorithms

Share2Dijkstra's AlgorithmShare2Floyd-WarshallShare2Breadth-First Search

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms