Graphs · Exercise 41 of 100

Bellman–Ford shortest paths

Bellman–Ford repeatedly scans the edges and lowers a destination's known cost whenever a cheaper route reaches it. It allows negative edge costs, and one fewer full scan than the number of vertices is enough if no negative-cost cycle is reachable from the start. Going around such a cycle repeatedly would keep lowering the cost of routes through it.

Try it yourself

Start with cost 0 at S and all others unknown. In each scan, process these one-way edges in order and use improvements immediately. The edges are A to T for 3, B to A for −5, S to A for 4 and S to B for 7. What cost does T have after three scans?

One-step hint

Keep one cost per vertex and update it as each edge is scanned. An improvement to A can affect T only when you next scan A to T.

Worked solution
  1. The first scan reaches A at 4 and B at 7. In the second scan A gives T a cost of 7, then B lowers A to 7 − 5 = 2.
  2. In the third scan the improved cost at A reaches T, lowering its cost to 2 + 3 = 5.
DSA compiler