Graph Theory37 sections · 1633 units
Open in Course

Basic Bellman-Ford Implementation

(The algorithm)

Here is the basic implementation:

function bellmanFord(n, edges, source):
    dist = array of size n, all infinity
    dist[source] = 0

    for round from 1 to n - 1:
        for (u, v, w) in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w

    return dist

After n1n-1 iterations, dist[v] contains the shortest distance from source to vv, assuming no negative cycles. If a negative cycle exists, some distances might be incorrect, but you can detect this with one more iteration.

This runs in O(VE)O(VE) time and uses O(V)O(V) space.