s LearnSqueak.com

SMALLTALK LAB

Bellman-Ford: shortest paths with negative edges

Relax a directed graph one snapshot at a time. Compute exact single-source costs, preserve unreachable vertices, and detect only the negative cycles the source can reach.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use native Squeak 6.1 and a Workspace. Select a complete checkpoint and choose Print it. All eight expressions are independent and install no classes. Vertices are integer indices 1 through V, V is at least 1, and every edge is #(from to weight). Use finite, unchanged input and exact Integer or Fraction weights. Expected results are Smalltalk expressions, not promises about whitespace in Print it. For the separate Morphic board, choose Do it and change stage from 0 through 4.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

01 - Give a directed graph an explicit contract

Number vertices 1 through V, and store each directed edge as #(from to weight). An edge does not imply its reverse. All endpoints and the source must be valid indices; this tutorial assumes that contract rather than silently repairing input. Use exact Integer or Fraction weights. Zero and negative weights are legal. Parallel edges and self-loops are legal too. nil means no discovered walk, not a large invented infinity.

Independent Workspace expression - select all, then Print it
| vertices edges distances |
vertices := #(A B C D E).
edges := #(#(3 4 2) #(2 3 -4) #(1 3 5) #(1 2 6)).
distances := Array new: vertices size.
distances at: 1 put: 0.
{edges size. distances}

Expected: #(4 #(0 nil nil nil nil))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Give a directed graph an explicit contract
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The empty walk gives source A cost zero. E is a real vertex even though no edge mentions it. A negative self-loop could later lower the source distance.

Download this checkpoint

02 - Relax one edge without doing arithmetic on nil

Relaxation asks whether a discovered walk to the tail, followed by this edge, improves the best known cost to its head. Guard the tail before adding the weight. A strict improvement replaces the old estimate; equality does nothing. Negative costs are ordinary numbers, so no special case is needed for subtraction.

Independent Workspace expression - select all, then Print it
| distances edge from candidate old |
distances := #(0 6 5 nil nil) copy.
edge := #(2 3 -4).
from := distances at: edge first.
from notNil ifTrue: [
 candidate := from + edge third.
 old := distances at: edge second.
 (old isNil or: [candidate < old]) ifTrue: [
  distances at: edge second put: candidate]].
distances

Expected: #(0 6 2 nil nil)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Relax one edge without doing arithmetic on nil
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change the edge to #(4 5 -9). Its tail is undiscovered, so the array must remain #(0 6 5 nil nil). Negative weights do not make unreachable vertices reachable.

Download this checkpoint

03 - Freeze the old estimates for one full pass

This version deliberately reads from distances and writes to a copy named next. A pass extends walks by at most one edge, regardless of edge ordering. Keeping the old entries also retains shorter walks. The edges are listed backwards along the chain to make propagation visible. An in-place implementation is also valid Bellman-Ford, but its intermediate states can propagate farther in one pass and obey a different trace invariant.

Independent Workspace expression - select all, then Print it
| edges distances next |
edges := #(#(3 4 2) #(2 3 -4) #(1 3 5) #(1 2 6)).
distances := #(0 nil nil nil nil) copy.
next := distances copy.
 edges do: [:edge | | from candidate old |
  from := distances at: edge first.
  from notNil ifTrue: [
   candidate := from + edge third.
   old := next at: edge second.
   (old isNil or: [candidate < old]) ifTrue: [
    next at: edge second put: candidate]]].
{distances. next}

Expected: #(#(0 nil nil nil nil) #(0 6 5 nil nil))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Freeze the old estimates for one full pass
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Even though B becomes 6 in next, the B-to-C edge reads the old nil at B. C first receives the direct cost 5, then improves on the next pass.

Download this checkpoint

04 - Use V minus one passes and inspect the history

After pass k, each entry is the cheapest source-to-vertex walk using at most k edges, or nil if none exists. Induction proves it: keep every old walk and try every possible last edge from a walk of at most k-1 edges. With no reachable negative cycle, removing cycles never increases cost, so a cheapest walk can be chosen simple and needs at most V-1 edges.

Independent Workspace expression - select all, then Print it
| edges distances next history |
edges := #(#(3 4 2) #(2 3 -4) #(1 3 5) #(1 2 6)).
distances := #(0 nil nil nil nil) copy.
history := OrderedCollection with: distances copy.
4 timesRepeat: [
 next := distances copy.
 edges do: [:edge | | from candidate old |
  from := distances at: edge first.
  from notNil ifTrue: [
   candidate := from + edge third.
   old := next at: edge second.
   (old isNil or: [candidate < old]) ifTrue: [
    next at: edge second put: candidate]]].
 distances := next.
 history add: distances copy].
history asArray

Expected: #(#(0 nil nil nil nil) #(0 6 5 nil nil) #(0 6 2 7 nil) #(0 6 2 4 nil) #(0 6 2 4 nil))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Use V minus one passes and inspect the history
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: D temporarily costs 7 via A-to-C-to-D, then improves to 4 via A-to-B-to-C-to-D. E remains nil. These are minimum costs from A, not a minimum spanning tree.

Download this checkpoint

05 - Detect a negative cycle reachable from the source

After V-1 passes, scan for any edge that can still improve an estimate from a reachable tail. Such an improvement proves a reachable negative cycle. Here B-to-C costs -4 and C-to-B costs 1, making a cycle of cost -3. Repeating it drives costs down without a finite minimum. This scan is diagnostic only: it does not mutate the distances or identify every affected vertex.

Independent Workspace expression - select all, then Print it
| edges distances next negative |
edges := #(#(1 2 2) #(2 3 -4) #(3 2 1) #(3 4 2)).
distances := #(0 nil nil nil) copy.
3 timesRepeat: [
 next := distances copy.
 edges do: [:edge | | from candidate old |
  from := distances at: edge first.
  from notNil ifTrue: [
   candidate := from + edge third.
   old := next at: edge second.
   (old isNil or: [candidate < old]) ifTrue: [
    next at: edge second put: candidate]]].
 distances := next].
negative := edges anySatisfy: [:edge | | from old |
 from := distances at: edge first.
 old := distances at: edge second.
 from notNil and: [old isNil or: [from + edge third < old]]].
{negative. distances}

Expected: #(true #(0 -1 -2 0))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Detect a negative cycle reachable from the source
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The finite numbers are only bounded-walk estimates when negative is true. B, C and downstream D have no finite minimum here; A still has minimum zero. Do not label every vertex as unbounded.

Download this checkpoint

06 - Ignore a negative cycle in a disconnected component

This is a single-source question, not a search for negative cycles anywhere in the graph. C and D have a negative cycle, but A cannot reach it. Guarding the tail prevents that disconnected cycle from contaminating either the distances or the cycle flag. To detect a cycle anywhere, a different initialization is needed, such as a new source with zero-cost edges to every original vertex.

Independent Workspace expression - select all, then Print it
| edges distances next negative |
edges := #(#(1 2 3) #(3 4 -2) #(4 3 1)).
distances := #(0 nil nil nil) copy.
3 timesRepeat: [
 next := distances copy.
 edges do: [:edge | | from candidate old |
  from := distances at: edge first.
  from notNil ifTrue: [
   candidate := from + edge third.
   old := next at: edge second.
   (old isNil or: [candidate < old]) ifTrue: [
    next at: edge second put: candidate]]].
 distances := next].
negative := edges anySatisfy: [:edge | | from old |
 from := distances at: edge first.
 old := distances at: edge second.
 from notNil and: [old isNil or: [from + edge third < old]]].
{negative. distances}

Expected: #(false #(0 3 nil nil))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Ignore a negative cycle in a disconnected component
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Start at vertex 3 instead by initializing #(nil nil 0 nil). The cycle flag becomes true. Reachability is always relative to the chosen source.

Download this checkpoint

07 - Package the algorithm with an explicit diagnostic flag

The block takes vertex count, directed edges and source. It returns #(hasReachableNegativeCycle distances). Only when the flag is false should callers treat all finite entries as shortest-path answers. When true, this simple interface reports failure for the overall query and leaves bounded-walk estimates for debugging. It intentionally does not return a cycle witness, paths, or a per-vertex unbounded marker.

Independent Workspace expression - select all, then Print it
| solve |
solve := [:count :edges :source | | distances next negative |
 distances := Array new: count.
 distances at: source put: 0.
 (count - 1) timesRepeat: [
  next := distances copy.
 edges do: [:edge | | from candidate old |
  from := distances at: edge first.
  from notNil ifTrue: [
   candidate := from + edge third.
   old := next at: edge second.
   (old isNil or: [candidate < old]) ifTrue: [
    next at: edge second put: candidate]]].
  distances := next].
 negative := edges anySatisfy: [:edge | | from old |
 from := distances at: edge first.
 old := distances at: edge second.
 from notNil and: [old isNil or: [from + edge third < old]]].
 {negative. distances}].
solve value: 5
 value: #(#(3 4 2) #(2 3 -4) #(1 3 5) #(1 2 6))
 value: 1

Expected: #(false #(0 6 2 4 nil))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Package the algorithm with an explicit diagnostic flag
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The source need not be 1. Calling with source 4 on this graph yields #(false #(nil nil nil 0 nil)), because none of its listed edges leaves D.

Download this checkpoint

08 - Test normal, disconnected and negative-cycle fixtures

Each fixture includes count, edges, source and the exact expected tuple. Tests cover a negative edge without a negative cycle, a disconnected negative cycle, a reachable negative cycle, an isolated source, a reachable zero-cost cycle and a negative self-loop at the only vertex. The last case runs zero relaxation passes, so the extra scan is essential even for V = 1.

Independent Workspace expression - select all, then Print it
| solve cases |
solve := [:count :edges :source | | distances next negative |
 distances := Array new: count.
 distances at: source put: 0.
 (count - 1) timesRepeat: [
  next := distances copy.
 edges do: [:edge | | from candidate old |
  from := distances at: edge first.
  from notNil ifTrue: [
   candidate := from + edge third.
   old := next at: edge second.
   (old isNil or: [candidate < old]) ifTrue: [
    next at: edge second put: candidate]]].
  distances := next].
 negative := edges anySatisfy: [:edge | | from old |
 from := distances at: edge first.
 old := distances at: edge second.
 from notNil and: [old isNil or: [from + edge third < old]]].
 {negative. distances}].
cases := {
 {5. #(#(3 4 2) #(2 3 -4) #(1 3 5) #(1 2 6)).
  1. #(false #(0 6 2 4 nil))}.
 {4. #(#(1 2 3) #(3 4 -2) #(4 3 1)).
  1. #(false #(0 3 nil nil))}.
 {4. #(#(1 2 2) #(2 3 -4) #(3 2 1) #(3 4 2)).
  1. #(true #(0 -1 -2 0))}.
 {3. #(). 2. #(false #(nil 0 nil))}.
 {3. #(#(1 2 2) #(2 3 -2) #(3 2 2)).
  1. #(false #(0 2 0))}.
 {1. #(#(1 1 -1)). 1. #(true #(0))}}.
cases allSatisfy: [:test |
 (solve value: test first value: test second value: test third)
  = test fourth]

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Test normal, disconnected and negative-cycle fixtures
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Break the tail guard or replace < with <= and rerun. The disconnected fixture catches invented reachability; the zero-cost cycle catches confusing equal-cost walks with negative cycles.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Bellman-Ford: shortest paths with negative edges native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

Dijkstra relies on nonnegative edge weights for its usual settlement rule. Bellman-Ford repeatedly revisits estimates and permits negative edges. Neither algorithm solves the undirected minimum spanning-tree problem handled by Kruskal.

A negative edge is not itself a negative cycle. A reachable negative cycle destroys finite minima for vertices on that cycle and those reachable from it, not necessarily for every reachable vertex. This implementation detects the condition but does not classify those vertices.

An unreachable negative cycle must not trigger the single-source flag. Never replace nil with zero, never add a weight to nil, and never use an arbitrary large finite sentinel as infinity.

After V-1 snapshot passes, any relaxable reachable edge proves a reachable negative cycle: without one, a minimum simple path has at most V-1 edges and all edge inequalities hold. Conversely, on a reachable negative cycle the inequalities cannot all hold, because summing them would imply zero is at most a negative total.

The snapshot invariant says at most k edges, not exactly k, and concerns walks while negative cycles are present. Copies and retaining old entries matter. Ordinary in-place Bellman-Ford remains correct, but it does not promise these same pass-by-pass arrays.

This array-copy implementation costs O(V*(V+E)) time: V-1 passes each copy V entries and scan E edges, followed by an O(E) diagnostic scan. Its auxiliary space is O(V), excluding the input and any saved history. The usual in-place implementation achieves O(V*E + V) time. Arithmetic and comparisons are assumed constant cost; arbitrary-precision weights can cost more.

The history and Morphic board intentionally retain extra arrays for teaching. You may stop early when a full pass changes no entry. Strict < avoids treating a zero-cost cycle as negative. Floating-point rounding can undermine exact cycle tests; the examples use exact arithmetic.

An undirected negative edge represented by two opposite directed edges creates a negative two-edge walk. Be explicit about directed graph semantics and about allowing repeated vertices in walks. The tutorial computes distances, not reconstructed paths.

Three practice challenges

Let a new source expose the hidden cycle

For checkpoint 6, start at C by using #(nil nil 0 nil). Predict the tuple after three passes and the diagnostic scan.

Show solution

After pass 1 the array is #(nil nil 0 -2); pass 2 gives #(nil nil -1 -2); pass 3 gives #(nil nil -1 -3). The returned tuple is #(true #(nil nil -1 -3)). A and B remain unreachable. The C-D-C cycle costs -1 and is now reachable.

Separate finite, unreachable and unbounded

In checkpoint 5, add a fifth vertex E with edge #(1 5 10), but no outgoing edges from E. Which vertices have a finite minimum, which are unbounded below, and which are unreachable?

Show solution

A has finite minimum 0 and E has finite minimum 10. B and C lie on the reachable negative cycle and D is downstream, so B, C and D are unbounded below. None is unreachable. The Boolean flag remains true, but a richer API would need a forward traversal from vertices affected by the extra relaxation to classify unbounded vertices.

Make early stopping safe

Describe where to test for a stable pass, whether the diagnostic scan is still safe, and what the best-case cost becomes for this copying implementation.

Show solution

After processing all edges into next, compare next = distances before replacing distances. If equal, all reachable edge inequalities already hold and another pass cannot change anything, so stop. Keeping the final diagnostic scan is safe and should return false. Including initialization, copying, comparison and one scan, a stable first pass takes O(V+E) time. Do not stop merely because one edge failed to relax.

Continue learning

Dijkstra Shortest Paths | Pathfinding | Dependency Order | Kruskal Spanning Tree | Collections | Testing

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.