Skip to content

Bellman-Ford shortest paths

networks

Level 3 of 3

Also called Bellman-Ford algorithm and Single-source shortest paths with negative lengths.

how it works

The idea on a small map, then the whole method on the watch page's first map. There A>B means a road from A to B, and places stand in two rows, A to D above and E to H below.

Bellman-Ford finds the shortest way from one place, the start, to every place it can reach, along one-way roads. A length can be below 0: that road pays you back. Write 0 at the start. Then go over the roads in rounds. A round takes the roads in letter order, by the place each leaves and then the place it leads to. It looks along each road from a place with a distance. The way along that road is the distance at its near end plus its length. If its far end has no distance, or a longer one, write the new length there. Stop when a whole round makes nothing shorter. A loop adding up below 0 is shorter every lap, so a way past it has no shortest, as section 4's question 6 draws. With no such loop, one round fewer than the places is enough, n−1n - 1 rounds for nn places. So if round n−1n - 1 still changed something, one last pass looks along the roads again. A road that can still make a way shorter means such a loop, and each place it leads on to gets −∞-\infty. This page counts the roads looked along. The code below, in the language Python, does the same. Where the code says sorted, that only keeps letter order, and the method needs no sort.

231-31ABCEF
Five one-way roads, each with its length, and the start at A. F to B is 3 below 0, so it pays back 3.
roadway along itwritten there beforewritten now
A to B0 + 2 is 2none2
A to E0 + 3 is 3none3
B to C2 + 1 is 3none3
E to F3 + 1 is 4none4
F to B4 - 3 is 121
Round 1, road by road, in letter order. B is written twice, as F to B pays back.
afterABCEF
the start0
round 101334
round 201234
round 301234
Round 2 carries B's new distance on to C. Round 3 makes nothing shorter, so the run stops, with 5 roads looked along in each round, 15 in all.
A road that pays back beats the straight road: 8 moments of its 36 steps, the steps between them left for the watch page
  1. step 1 of 36

    623-457-212-3A0BCDEFGH

    Start at A, 0 from itself. With this many places a shortest way has at most 7 roads, so at most 7 rounds of looking along every road will do.

    what it remembers to know where it is
    round
    not yet
    looking along
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 3 of 36

    623-457-212-3A0B6CDEFGH

    The road from A to B is 6 long, so through A it is 6 to B, shorter than any way found before. Write 6 at B.

    what it remembers to know where it is
    round
    1
    looking along
    A>B

    watch from here

  3. step 10 of 36

    623-457-212-3A0B1C11D13E2F5G9H10

    The road from F to B is -4 long, so through F it is 1 to B, shorter than any way found before. Write 1 at B.

    what it remembers to know where it is
    round
    1
    looking along
    F>B

    watch from here

  4. step 13 of 36

    623-457-212-3A0B1C11D13E2F5G9H10

    Round 2: look along every road from a place with a distance, in letter order.

    what it remembers to know where it is
    round
    2
    looking along
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  5. step 16 of 36

    623-457-212-3A0B1C6D13E2F5G9H10

    The road from B to C is 5 long, so through B it is 6 to C, shorter than any way found before. Write 6 at C.

    what it remembers to know where it is
    round
    2
    looking along
    B>C

    watch from here

  6. step 24 of 36

    623-457-212-3A0B1C6D8E2F5G4H5

    Round 3: look along every road from a place with a distance, in letter order.

    what it remembers to know where it is
    round
    3
    looking along
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  7. step 35 of 36

    623-457-212-3A0B1C6D8E2F5G4H5

    Round 3 made nothing shorter, so no later round could either: every distance is final.

    what it remembers to know where it is
    round
    3
    looking along
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  8. step 36 of 36

    623-457-212-3A0B1C6D8E2F5G4H5

    Done: 8 of the 8 places can be reached, and each distance is the shortest way from the start.

    what it remembers to know where it is
    round
    3
    looking along
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. write 0 at the start; no other place has a distance yetPython lines 13, 14 and 15
  2. round after round, at most one fewer than the places, look along every road from a place with a distancePython lines 17, 18, 19, 20, 21, 22 and 23
  3. if the way along it is shorter, write the new distance at its endPython lines 24, 25 and 26
  4. if not, keep the distance therePython line 27
  5. a round with nothing made shorter: every distance is finalPython lines 28 and 29
  6. after the last round, a road that still makes a way shorter is on, or past, a loop that keeps getting shorterPython lines 30, 31 and 32
  7. every place such a loop reaches has no shortest way: write -∞ therePython lines 33, 34, 35, 36, 37, 38, 39, 40, 41 and 42
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def bellman_ford(roads, start):
    """Find the shortest way from start to every place it can reach.

    roads is a list of (from, to, length), each running one way, a length
    below 0 paying you back. Returns a dict, a table, of what each place has
    written at the end: its shortest way, or "-∞" if a loop that keeps getting
    shorter can reach it. A place start cannot reach is left out.
    """
    return look_along_roads(roads, start)[0]


def look_along_roads(roads, start):
    in_order = sorted(roads)  # letter order, only so this page has one answer
    places = {place for a, b, _ in roads for place in (a, b)}
    distance = {start: 0}  # write 0 at the start
    rounds = 0
    for _ in range(len(places) - 1):  # at most one fewer than the places
        rounds += 1
        changed = False
        for a, b, length in in_order:  # every road
            if a not in distance:  # only from a place with a distance
                continue
            total = distance[a] + length  # the way through a
            if b not in distance or total < distance[b]:  # shorter?
                distance[b] = total  # write the new distance at its end
                changed = True
            # if not, keep the distance there
        if not changed:  # nothing made shorter: every distance is final
            return distance, rounds
    # One more look along every road, after the last round.
    # A road that still makes a way shorter is on, or past, a loop that keeps getting shorter.
    lost = {b for a, b, length in in_order if a in distance and distance[a] + length < distance[b]}
    waiting = list(lost)
    while waiting:  # every place such a road leads on to, each place once
        here = waiting.pop()
        for a, b, _ in roads:
            if a == here and b not in lost:
                lost.add(b)
                waiting.append(b)
    for place in lost:
        distance[place] = "-∞"  # going round once more is always shorter
    return distance, rounds

how it scales

The plot counts the roads looked along on two lines of nn places, every road 1 long, measured from 10 to 1,000 places. One runs in letter order, from the first letter. The other is the same line backwards, from the last letter.

Each mark across or up is ten times the one before. In letter order the count climbs one mark up for each mark across: 198 at 100 places and 1,998 at 1,000, about 10 times. Backwards it climbs two: 5,049 at 100 places and 500,499 at 1,000, about 99 times. A slope of 1 means the cost grows as nn, and a slope of 2 as the square of nn.

roads looked along, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, n, ten times more at each mark to the right

  • the same line backwardssolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • a line in letter ordersolid where measured by running it; dashed where its formula carries it on to ten million
how long the same line backwards takes, at a billion roads a second
nnroads looked alongtime
1,000500,499about 500 microseconds
100,0005,000,049,999about 5 seconds
10,000,00050,000,004,999,999about 14 hours

The roads looked along are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count Bellman-Ford's roads looked along yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it runs two maps of n
places: a line in letter order, and the same line backwards. It prints the
roads looked along for each. The counts are the same on any computer; only
the time differs.
"""


def bellman_ford(roads, start):
    """Find the shortest way from start to every place it can reach.

    roads is a list of (from, to, length), each running one way, a length
    below 0 paying you back. Returns a dict, a table, of what each place has
    written at the end: its shortest way, or "-∞" if a loop that keeps getting
    shorter can reach it. A place start cannot reach is left out.
    """
    return look_along_roads(roads, start)[0]


def look_along_roads(roads, start):
    in_order = sorted(roads)  # letter order, only so this page has one answer
    places = {place for a, b, _ in roads for place in (a, b)}
    distance = {start: 0}  # write 0 at the start
    rounds = 0
    for _ in range(len(places) - 1):  # at most one fewer than the places
        rounds += 1
        changed = False
        for a, b, length in in_order:  # every road
            if a not in distance:  # only from a place with a distance
                continue
            total = distance[a] + length  # the way through a
            if b not in distance or total < distance[b]:  # shorter?
                distance[b] = total  # write the new distance at its end
                changed = True
            # if not, keep the distance there
        if not changed:  # nothing made shorter: every distance is final
            return distance, rounds
    # One more look along every road, after the last round.
    # A road that still makes a way shorter is on, or past, a loop that keeps getting shorter.
    lost = {b for a, b, length in in_order if a in distance and distance[a] + length < distance[b]}
    waiting = list(lost)
    while waiting:  # every place such a road leads on to, each place once
        here = waiting.pop()
        for a, b, _ in roads:
            if a == here and b not in lost:
                lost.add(b)
                waiting.append(b)
    for place in lost:
        distance[place] = "-∞"  # going round once more is always shorter
    return distance, rounds


def count(roads, start):
    """How many roads the run looks along, round by round, and the last pass if it comes to one."""
    in_order = sorted(roads)
    places = {place for a, b, _ in roads for place in (a, b)}
    distance = {start: 0}
    looks = 0
    for _ in range(len(places) - 1):
        changed = False
        for a, b, length in in_order:
            if a not in distance:
                continue
            looks += 1
            total = distance[a] + length
            if b not in distance or total < distance[b]:
                distance[b] = total
                changed = True
        if not changed:
            return looks
    return looks + sum(1 for a, _, _ in in_order if a in distance)


def names(n):
    """n names that sort in the order they count."""
    return [f"p{k:04}" for k in range(1, n + 1)]


def forwards(n):
    """A line in letter order, each road 1 long: n - 1 roads, from the first name."""
    places = names(n)
    return [(places[k], places[k + 1], 1) for k in range(n - 1)], places[0]


def backwards(n):
    """The same line backwards: each road to the name before, from the last name."""
    places = names(n)
    return [(places[k + 1], places[k], 1) for k in range(n - 1)], places[-1]


if __name__ == "__main__":
    print(f"{'n':>6} {'in letter order':>16} {'backwards':>11}")
    for n in [10, 100, 1000]:
        print(f"{n:>6} {count(*forwards(n)):>16} {count(*backwards(n)):>11}")

best, worst and average

Here best names a line in letter order and worst the same line backwards: kinds of map. Neither is the fewest or the most a run can look along. A start that reaches few of the places can look along fewer. On any map of nn places and mm roads the ceiling is n×mn \times m looks, and section 4's question 5 shows a map costing far more than both lines. No average is worked out. With 5 places, the line in letter order costs 8 looks and backwards 14.

A case is one kind of map, such as a line in letter order. A bound says how fast that case's cost grows as places are added.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta line in letter orderworstthe same line backwards
roads looked along2(n−1)2(n - 1), each road twice(n−1)(n+2)2\frac{(n - 1)(n + 2)}{2}
rounds2, from 3 places onn−1n - 1, all that are allowed
how the roads looked along grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n2)\Omega(n^2)

extra memory: A distance at each place, and, when a loop is found, a list of the places it reaches.

Extra memory is the room it needs on top of the input itself, while it runs.

1111ABCDG
A line of 5 in letter order, from A. Round 1 takes the roads as the line runs, so it writes every place.
1111ABCDG
The same line backwards, from G. Only G has a distance, so round 1 skips B to A, C to B and D to C, and looks along G to D alone. Each round gets one road further.
mapplacesroadsroundslooks
a line of 5 in letter order5428
the same line backwards54414
the small map55315
the first map810330
A look is one road. Backwards, a round skips the roads from places with no distance yet, and a last pass adds 4 looks.

where the formula comes from

Question 1 says how many roads a shortest way needs, and 2 why that many rounds are enough. Questions 3 and 4 count the two lines, 5 any map, and 6 what a loop does.

Question 1: with no loop adding up below 0 that the start can reach, how many roads does a shortest way need? Let SS be a ceiling on them.
  1. the move: a place comes twice

    the line:
    a way of n roadsmeets a place twice\begin{gathered} \text{a way of } n \text{ roads} \\ \text{meets a place twice} \end{gathered}

    why it is allowed: With 5 places, a way of 5 roads stands at 6 places, counting repeats, so one comes twice. In general a way of nn roads stands at one more than nn places. The roads between a place's two visits are a loop.

  2. the move: cut the loop out

    the line:
    without the loop, the wayis as short or shorter\begin{gathered} \text{without the loop, the way} \\ \text{is as short or shorter} \end{gathered}
    231-312ABCEF
    A, E, F, B, C, F, B adds up to 1. The loop B, C, F, drawn heavy, adds up to 0. Cut it out, and A, E, F, B also adds up to 1, with 3 fewer roads.

    why it is allowed: The start reaches this loop, so it adds up to at least 0. So the way without it is as short or shorter. Do this until no place comes twice.

  3. the move: no place twice

    the line:
    S=n−1S = n - 1

    why it is allowed: A way with no place twice stands at nn places at most, so it has at most n−1n - 1 roads. For 5 places, 4.

try it with a small nn: at n=5n = 5, line 3 gives S=4S = 4, which you can work out by hand

Question 2: with no such loop, why are n−1n - 1 rounds enough? Let RR be the most a run may need.
  1. the move: only real ways

    the line:
    a distance is the lengthof a way that exists\begin{gathered} \text{a distance is the length} \\ \text{of a way that exists} \end{gathered}

    why it is allowed: The start's 0 is the way of no roads. Each new distance is a way to the near end plus one road. So no distance goes below the shortest way, the smallest of them all.

  2. the move: the start is right

    the line:
    before round 1,the start is right\begin{gathered} \text{before round 1,} \\ \text{the start is right} \end{gathered}

    why it is allowed: A place is right when its distance is its shortest way. With no such loop, no way back to the start adds up below 0, so its 0 is the shortest.

  3. the move: one road a round

    the line:
    after round k, a place whoseshortest way has k roads is right\begin{gathered} \text{after round } k, \text{ a place whose} \\ \text{shortest way has } k \text{ roads is right} \end{gathered}
    placeits shortest wayroads on itmust be right bywas right after
    EA, E1round 1round 1
    FA, E, F2round 2round 1
    BA, E, F, B3round 3round 1
    CA, E, F, B, C4round 4round 2
    The small map. Letter order can bring a place in early, as with F, B and C. By line 3 it is never late.

    why it is allowed: kk counts both rounds and roads. Line 2 is the claim for no rounds, and each round carries it one further, so none gives 1, 1 gives 2, and so on. So say it holds one round earlier. Take a place whose shortest way has kk roads, and let uu be the place before it, so the way up to uu has one road fewer. That way is shortest to uu, or the whole way could be shorter, so uu is right. Round kk looks along the last road. So the place gets that way or better, and by line 1 nothing lower.

  4. the move: so n - 1 rounds

    the line:
    R=n−1R = n - 1

    why it is allowed: A place stays right, as by line 1 nothing goes lower. By question 1 no place needs more than n−1n - 1 roads, so by line 3 each is right after round n−1n - 1. A round that changes nothing ends the run sooner, as the next would read the same numbers. The same line backwards writes a new place in every round, so a run can need them all. For 5 places, 4.

try it with a small nn: at n=5n = 5, line 4 gives R=4R = 4, which you can work out by hand

Question 3: how many roads, KK, does a line in letter order look along?
  1. the move: two looks at each road

    the line:
    K=2(n−1)K = 2(n - 1)
    the line of 5 in letter orderroads looked alongplaces written
    round 144
    round 240
    all8
    From A. Round 1 reaches the end of the line.

    why it is allowed: Letter order takes the roads as the line runs, so round 1 writes each place in turn, looking along all n−1n - 1 roads. Round 2 looks along them again, finds nothing shorter and stops. With 2 places only round 1 is allowed, so the last pass takes round 2's place. For 5 places, 8.

  2. the move: a ceiling

    the line:
    K≤2nK \le 2n

    why it is allowed: 2(n−1)2(n - 1) is below 2n2n. For 5 places, KK is 8, at most 10.

  3. the move: read the bound

    the line:
    K∈O(n)K \in O(n)

    why it is allowed: By line 2, with the fixed multiple 2. ∈\in reads is in, and O(n)O(n) means at most a fixed multiple of nn, from some nn on.

  4. the move: a floor

    the line:
    K≥nK \ge n

    why it is allowed: KK is nn, plus nn take away 2, and from 2 places on nn is at least 2. For 5 places, KK is 8, at least 5.

  5. the move: read the bound

    the line:
    K∈Ω(n)K \in \Omega(n)

    why it is allowed: By line 4, with the fixed multiple 1. Ω(n)\Omega(n) means at least a fixed multiple of nn, above 0, from some nn on.

  6. the move: both together

    the line:
    K∈Θ(n)K \in \Theta(n)

    why it is allowed: Lines 3 and 5 bound KK by the same growth, only a fixed multiple apart. Θ(n)\Theta(n) means both.

try it with a small nn: at n=5n = 5, line 1 gives K=8K = 8, which you can work out by hand

Question 4: how many roads, WW, does the same line backwards look along?
  1. the move: round by round

    the line:
    W=1+2+⋯+(n−1)+(n−1)W = 1 + 2 + \dots + (n - 1) + (n - 1)
    the line of 5 backwardsroads looked alongplace written
    round 11D
    round 22C
    round 33B
    round 44A
    the last pass4none
    all14
    From G. Each round writes one place, one road further along.

    why it is allowed: The road from the start comes last in letter order, so round 1 looks along it alone. On the line of 5, G to D writes D, but D to C came earlier in that round, so D to C waits for round 2. So each round gives just one more place a distance, and round kk looks along kk roads. Round n−1n - 1 still writes a place, so the last pass looks along all n−1n - 1.

  2. the move: add up to n - 1

    the line:
    W=n(n−1)2+(n−1)W = \frac{n(n - 1)}{2} + (n - 1)
    Two staircases of 1 to 4 squares fill 4 columns of 5, which is 20 squares, so one staircase is 10.

    why it is allowed: Write 1+2+⋯+(n−1)1 + 2 + \dots + (n - 1) twice, the second backwards. Each of its n−1n - 1 pairs adds to nn, so halve nn times n−1n - 1. For 5 places, 10, then 4 more.

  3. the move: take out n - 1

    the line:
    W=(n−1)(n2+1)W = (n - 1)\left(\frac{n}{2} + 1\right)

    why it is allowed: Both parts hold n−1n - 1. Take it out, and a half of nn, plus 1, is left.

  4. the move: one fraction

    the line:
    W=(n−1)(n+2)2W = \frac{(n - 1)(n + 2)}{2}

    why it is allowed: Write the 1 as 2 over 2, and the two halves join. For 5 places, 14.

  5. the move: multiply out

    the line:
    W=n2+n−22W = \frac{n^2 + n - 2}{2}

    why it is allowed: Each part of the first bracket times each part of the second. For 5 places, 28 over 2.

  6. the move: a ceiling

    the line:
    W≤n2W \le n^2

    why it is allowed: The top is below n2n^2 and nn added, and nn is at most n2n^2, so the top is at most twice n2n^2. Halve it. For 5 places, WW is 14, at most 25.

  7. the move: read the bound

    the line:
    W∈O(n2)W \in O(n^2)

    why it is allowed: By line 6, with the fixed multiple 1.

  8. the move: a floor

    the line:
    W≥n22W \ge \frac{n^2}{2}

    why it is allowed: From 2 places on, nn take away 2 is at least 0, so the top is at least n2n^2. Halve it. For 5 places, WW is 14, at least 12.5.

  9. the move: read the bound

    the line:
    W∈Ω(n2)W \in \Omega(n^2)
    looksplaces0204060801000246810looksplaces0204060801000246810
    • n2n^2
    • WW
    • n22\frac{n^2}{2}
    From 2 places on, WW stays between its floor and its ceiling.

    why it is allowed: By line 8, with the fixed multiple a half.

  10. the move: both together

    the line:
    W∈Θ(n2)W \in \Theta(n^2)

    why it is allowed: Lines 7 and 9 bound WW by the same growth.

try it with a small nn: at n=5n = 5, line 1 gives W=14W = 14, which you can work out by hand

Question 5: on any map of mm roads, why at most n×mn \times m looks? Let PP be the most passes over them.
  1. the move: how many passes

    the line:
    P=nP = n

    why it is allowed: A pass is a round or the last pass, and a run has at most n−1n - 1 rounds and one last pass. For 5 places, 5.

  2. the move: each pass

    the line:
    each pass: at mostm looks\begin{gathered} \text{each pass: at most} \\ m \text{ looks} \end{gathered}

    why it is allowed: A pass looks along each road once at most. For the small map, at most 5.

  3. the move: multiply

    the line:
    at most n×m looks\begin{gathered} \text{at most } n \times m \text{ looks} \end{gathered}
    1555155151ABCDE
    Every pair of 5, each road from a later letter to an earlier, from E. Roads between neighbouring letters are 1 and the rest 5. So the short line from E to A is the shortest way to each place, and each round gets one road along it.
    mapn×mn \times mlooks
    a line of 5 in letter order208
    the same line backwards2014
    every pair of 5, a short line5044
    On every pair of 5, round 1 looks along E's 4 roads alone, and they give every place a distance. So each of 3 more rounds looks along all 10, and the last pass too, and 4 + 30 + 10 is 44.

    why it is allowed: Lines 1 and 2 multiplied. The small map's ceiling is 25, and its run looks along 15.

  4. the move: every read

    the line:
    passes and finding: at most2×n×m reads\begin{gathered} \text{passes and finding: at most} \\ 2 \times n \times m \text{ reads} \end{gathered}

    why it is allowed: A read is any road a pass turns to, looked along or skipped. Round 1 of the line of 5 backwards makes 4 reads and 1 look. So the passes make at most n×mn \times m reads. Finding every place past a loop takes each such place once and reads all the roads for it, another n×mn \times m at most. Listing the places first adds mm more, which line 5's fixed multiple covers.

  5. the move: read the bound

    the line:
    the whole method in O(nm),in books, O(VE)\begin{gathered} \text{the whole method in } O(nm), \\ \text{in books, } O(VE) \end{gathered}

    why it is allowed: By line 4. A computer does each read in a fixed few actions, so the whole stays at most a fixed multiple of n×mn \times m. On a line, mm is n−1n - 1, so this ceiling grows as the square of nn. The same line backwards reaches that growth, and the line in letter order stays far under it. In books VV is the places and EE the roads, not place E.

try it with a small nn: at n=5n = 5, line 1 gives P=5P = 5, which you can work out by hand

Question 6: what does such a loop do, and how does the last pass find it? Let LL be the rounds before that pass.
  1. the move: no shortest way

    the line:
    past such a loop,no way is shortest\begin{gathered} \text{past such a loop,} \\ \text{no way is shortest} \end{gathered}
    42-513ABCFG
    The loop B, C, F, drawn heavy, adds up to 2 below 0, so each lap is 2 shorter. G is past it.
    afterABCFG
    round 102614
    round 2004-12
    round 30-22-30
    round 40-40-5-2
    Each round, each place from B on is 2 lower, one lap's worth.

    why it is allowed: Such a loop is one the start can reach, adding up below 0. Go round it once more and a way through it is shorter, as often as you like. So a place it can reach has no shortest way.

  2. the move: no such loop

    the line:
    no such loop: the lastpass changes nothing\begin{gathered} \text{no such loop: the last} \\ \text{pass changes nothing} \end{gathered}

    why it is allowed: By question 2 each place the start reaches is right after round n−1n - 1, and by its line 1 no distance goes lower. So no road can make a way shorter.

  3. the move: such a loop

    the line:
    such a loop: a road on it canalways make a way shorter\begin{gathered} \text{such a loop: a road on it can} \\ \text{always make a way shorter} \end{gathered}
    roadway along itwritten at its far endshorter?
    B to C-4 + 2 is -20yes
    C to F0 - 5 is -5-5no
    F to B-5 + 1 is -4-4no
    The last pass on the loop, after round 4. B to C still makes a way shorter. A last pass writes no distance, so C keeps its 0 for the next row.

    why it is allowed: Say each place on it has a distance, and no road on it makes a way shorter. Then each far end is at most its near end plus the road's length. With each letter for its place's distance, on this map C is at most B + 2, F at most C - 5, and B at most F + 1. Add the three, and B + C + F is at most itself take away 2, so 0 is at most -2. That is false. On any such loop the distances cancel the same way, leaving 0 at most its total, which is below 0. So some road on it makes a way shorter.

  4. the move: all the rounds

    the line:
    L=n−1L = n - 1

    why it is allowed: Line 1's table shows it, as all 4 rounds change something. Now any such loop. Say a round changed nothing. Then every road from a place with a distance already has a distance at its far end, so each place on the loop has one. By line 3 a road on the loop then makes a way shorter, so that round did change something. So the run uses all n−1n - 1 rounds. With repeats cut out, a way to a place on the loop has at most n−1n - 1 roads, and each round writes a distance at least one road further. So by round n−1n - 1 each place on it has one. For 5 places, 4.

  5. the move: every place past it

    the line:
    the far end, and all itleads on to: −∞\begin{gathered} \text{the far end, and all it} \\ \text{leads on to: } -\infty \end{gathered}

    why it is allowed: Take a place no such loop reaches. A way to it never passes such a loop, or that loop would reach it. So question 2's steps hold along that way, and the place is right. The near end of a road into it is also a place no such loop reaches, or the loop would reach it along that road. So that end is right too, and the road cannot beat what is written. So a road that still makes a way shorter ends at a place such a loop reaches, and by line 3 one ends on each such loop. The run writes −∞-\infty there and at every place it leads on to, and nowhere else. Here that is B, C, F and G, and A keeps 0.

try it with a small nn: at n=5n = 5, line 4 gives L=4L = 4, which you can work out by hand

count it yourself

A line of 3 in letter order, A, B and E, every road 1 long, from A. The watch page writes this map as A>B 1, B>E 1; A. There A>B 1 means a road from A to B, 1 long, and the letter after the semicolon is the start. The last columns are running totals.

A>B 1, B>E 1; A, every step written down
stepwhat happensroads looked alongrounds
1Start at A, 0 from itself. With this many places a shortest way has at most 2 roads, so at most 2 rounds of looking along every road will do.00
2Round 1: look along every road from a place with a distance, in letter order.01
3The road from A to B is 1 long, so through A it is 1 to B, shorter than any way found before. Write 1 at B.11
4The road from B to E is 1 long, so through B it is 2 to E, shorter than any way found before. Write 2 at E.21
5Round 2: look along every road from a place with a distance, in letter order.22
6The road from A to B is 1 long, so through A it is 1 to B, no shorter than the 1 written there. Keep 1.32
7The road from B to E is 1 long, so through B it is 2 to E, no shorter than the 2 written there. Keep 2.42
8Round 2 made nothing shorter, so no later round could either: every distance is final.42
9Done: 3 of the 3 places can be reached, and each distance is the shortest way from the start.42

In all, 4 roads looked along. The formula from section 4, 2(n−1)2(n - 1), gives K=4K = 4 at n=3n = 3: the same.

where you meet it

Papers from the 1950s set it out, and routers and ready-made code still use its idea.

  • Bellman's 1958 paper

    Richard Bellman set out finding routes between cities by improving each distance from the others, again and again. Lester Ford had described much the same in 1956, so the method carries both names.

    source: R. Bellman, On a routing problem (opens in a new tab), Quarterly of Applied Mathematics 16(1), and the books' volume three, chapter 35

  • Routers running RIP

    A router is a machine that passes messages between networks. One running RIP, a set of rules routers share, tells its neighbours how far it is from each network. It takes a shorter way when it hears one, a hop from one router to the next usually counting 1. That is this page's look along a road, run by many machines at once.

    source: G. Malkin, RFC 2453, RIP Version 2 (opens in a new tab), its section on the protocol's distance vector algorithm, and the books' volume three, chapter 35

  • networkx

    networkx, ready-made Python code for networks, offers a variant of this method, rereading only the roads from places just changed. It also has a separate check for a loop adding up below 0.

    source: the networkx source, weighted.py (opens in a new tab), its bellman_ford_path_length and negative_edge_cycle

what is used instead

With no length below 0, use Dijkstra's method, as section 7 sets out. When every road counts 1, use breadth-first search. For the shortest way between every two places at once, use Floyd-Warshall, which has its own page.

how it compares

Dijkstra's method picks the nearest place with no final distance, settles it, and never writes it again. So a road below 0 can come too late. This method settles nothing and looks again. On the small map Dijkstra's settles B at 2 before F has a distance, and F to B then finds B settled.

methodlooks alonglengths below 0
this page's methodeach road from a place with a distance, every passright, and it marks each place such a loop reaches
Dijkstra's methodeach road at most once, from the nearest placecan be wrong, with no warning
breadth-first searcheach road at most once from each end, as its roads run both ways, every road counting 1takes no lengths
Dijkstra's looks along each road at most once, and this method may look along each in every pass. So reach for this method where a road pays back.
placethis page's methodDijkstra's method
A00
B12
C23
E33
F44
The small map. Dijkstra's ends with B and C too long, and says nothing.

race them on one row of your own