Bellman-Ford shortest paths
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, rounds for places. So if round 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 . 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.
| road | way along it | written there before | written now |
|---|---|---|---|
| A to B | 0 + 2 is 2 | none | 2 |
| A to E | 0 + 3 is 3 | none | 3 |
| B to C | 2 + 1 is 3 | none | 3 |
| E to F | 3 + 1 is 4 | none | 4 |
| F to B | 4 - 3 is 1 | 2 | 1 |
| after | A | B | C | E | F |
|---|---|---|---|---|---|
| the start | 0 | ||||
| round 1 | 0 | 1 | 3 | 3 | 4 |
| round 2 | 0 | 1 | 2 | 3 | 4 |
| round 3 | 0 | 1 | 2 | 3 | 4 |
step 1 of 36
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.
step 3 of 36
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
step 10 of 36
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
step 13 of 36
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.
step 16 of 36
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
step 24 of 36
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.
step 35 of 36
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.
step 36 of 36
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- write 0 at the start; no other place has a distance yetPython lines 13, 14 and 15
- 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
- if the way along it is shorter, write the new distance at its endPython lines 24, 25 and 26
- if not, keep the distance therePython line 27
- a round with nothing made shorter: every distance is finalPython lines 28 and 29
- 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
- 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 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 , and a slope of 2 as the square of .
roads looked along, ten times more at each mark up
, 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
| roads looked along | time | |
|---|---|---|
| 1,000 | 500,499 | about 500 microseconds |
| 100,000 | 5,000,049,999 | about 5 seconds |
| 10,000,000 | 50,000,004,999,999 | about 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 places and roads the ceiling is 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.
| besta line in letter order | worstthe same line backwards | |
|---|---|---|
| roads looked along | , each road twice | |
| rounds | 2, from 3 places on | , all that are allowed |
| how the roads looked along grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
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.
| map | places | roads | rounds | looks |
|---|---|---|---|---|
| a line of 5 in letter order | 5 | 4 | 2 | 8 |
| the same line backwards | 5 | 4 | 4 | 14 |
| the small map | 5 | 5 | 3 | 15 |
| the first map | 8 | 10 | 3 | 30 |
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.
the move: a place comes twice
the line: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 roads stands at one more than places. The roads between a place's two visits are a loop.
the move: cut the loop out
the line: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.
guess it, thenthe move: no place twice
the line:why it is allowed: A way with no place twice stands at places at most, so it has at most roads. For 5 places, 4.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: only real ways
the line: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.
the move: the start is right
the line: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.
guess it, thenthe move: one road a round
the line:place its shortest way roads on it must be right by was right after E A, E 1 round 1 round 1 F A, E, F 2 round 2 round 1 B A, E, F, B 3 round 3 round 1 C A, E, F, B, C 4 round 4 round 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: 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 roads, and let be the place before it, so the way up to has one road fewer. That way is shortest to , or the whole way could be shorter, so is right. Round looks along the last road. So the place gets that way or better, and by line 1 nothing lower.
guess it, thenthe move: so n - 1 rounds
the line:why it is allowed: A place stays right, as by line 1 nothing goes lower. By question 1 no place needs more than roads, so by line 3 each is right after round . 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.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: two looks at each road
the line:the line of 5 in letter order roads looked along places written round 1 4 4 round 2 4 0 all 8 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 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.
the move: a ceiling
the line:why it is allowed: is below . For 5 places, is 8, at most 10.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 2, with the fixed multiple 2. reads is in, and means at most a fixed multiple of , from some on.
guess it, thenthe move: a floor
the line:why it is allowed: is , plus take away 2, and from 2 places on is at least 2. For 5 places, is 8, at least 5.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 1. means at least a fixed multiple of , above 0, from some on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 3 and 5 bound by the same growth, only a fixed multiple apart. means both.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: round by round
the line:the line of 5 backwards roads looked along place written round 1 1 D round 2 2 C round 3 3 B round 4 4 A the last pass 4 none all 14 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 looks along roads. Round still writes a place, so the last pass looks along all .
the move: add up to n - 1
the line: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 twice, the second backwards. Each of its pairs adds to , so halve times . For 5 places, 10, then 4 more.
guess it, thenthe move: take out n - 1
the line:why it is allowed: Both parts hold . Take it out, and a half of , plus 1, is left.
guess it, thenthe move: one fraction
the line:why it is allowed: Write the 1 as 2 over 2, and the two halves join. For 5 places, 14.
guess it, thenthe move: multiply out
the line:why it is allowed: Each part of the first bracket times each part of the second. For 5 places, 28 over 2.
guess it, thenthe move: a ceiling
the line:why it is allowed: The top is below and added, and is at most , so the top is at most twice . Halve it. For 5 places, is 14, at most 25.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: From 2 places on, take away 2 is at least 0, so the top is at least . Halve it. For 5 places, is 14, at least 12.5.
guess it, thenthe move: read the bound
the line:From 2 places on, stays between its floor and its ceiling. why it is allowed: By line 8, with the fixed multiple a half.
guess it, thenthe move: both together
the line:why it is allowed: Lines 7 and 9 bound by the same growth.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: how many passes
the line:why it is allowed: A pass is a round or the last pass, and a run has at most rounds and one last pass. For 5 places, 5.
the move: each pass
the line:why it is allowed: A pass looks along each road once at most. For the small map, at most 5.
guess it, thenthe move: multiply
the line: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. map looks a line of 5 in letter order 20 8 the same line backwards 20 14 every pair of 5, a short line 50 44 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.
guess it, thenthe move: every read
the line: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 reads. Finding every place past a loop takes each such place once and reads all the roads for it, another at most. Listing the places first adds more, which line 5's fixed multiple covers.
guess it, thenthe move: read the bound
the line: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 . On a line, is , so this ceiling grows as the square of . The same line backwards reaches that growth, and the line in letter order stays far under it. In books is the places and the roads, not place E.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: no shortest way
the line:The loop B, C, F, drawn heavy, adds up to 2 below 0, so each lap is 2 shorter. G is past it. after A B C F G round 1 0 2 6 1 4 round 2 0 0 4 -1 2 round 3 0 -2 2 -3 0 round 4 0 -4 0 -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.
the move: no such loop
the line:why it is allowed: By question 2 each place the start reaches is right after round , and by its line 1 no distance goes lower. So no road can make a way shorter.
guess it, thenthe move: such a loop
the line:road way along it written at its far end shorter? B to C -4 + 2 is -2 0 yes C to F 0 - 5 is -5 -5 no F to B -5 + 1 is -4 -4 no 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.
guess it, thenthe move: all the rounds
the line: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 rounds. With repeats cut out, a way to a place on the loop has at most roads, and each round writes a distance at least one road further. So by round each place on it has one. For 5 places, 4.
guess it, thenthe move: every place past it
the line: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 there and at every place it leads on to, and nowhere else. Here that is B, C, F and G, and A keeps 0.
guess it, then
try it with a small : at , line 4 gives , 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.
| step | what happens | roads looked along | rounds |
|---|---|---|---|
| 1 | Start 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. | 0 | 0 |
| 2 | Round 1: look along every road from a place with a distance, in letter order. | 0 | 1 |
| 3 | The 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. | 1 | 1 |
| 4 | The 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. | 2 | 1 |
| 5 | Round 2: look along every road from a place with a distance, in letter order. | 2 | 2 |
| 6 | The 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. | 3 | 2 |
| 7 | The 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. | 4 | 2 |
| 8 | Round 2 made nothing shorter, so no later round could either: every distance is final. | 4 | 2 |
| 9 | Done: 3 of the 3 places can be reached, and each distance is the shortest way from the start. | 4 | 2 |
In all, 4 roads looked along. The formula from section 4, , gives at : 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.
| method | looks along | lengths below 0 |
|---|---|---|
| this page's method | each road from a place with a distance, every pass | right, and it marks each place such a loop reaches |
| Dijkstra's method | each road at most once, from the nearest place | can be wrong, with no warning |
| breadth-first search | each road at most once from each end, as its roads run both ways, every road counting 1 | takes no lengths |
| place | this page's method | Dijkstra's method |
|---|---|---|
| A | 0 | 0 |
| B | 1 | 2 |
| C | 2 | 3 |
| E | 3 | 3 |
| F | 4 | 4 |