s LearnSqueak.com

SMALLTALK LAB

Floyd–Warshall in Squeak: Shortest Paths Between Every Pair

Turn a directed graph into an all-pairs route table, reconstruct a path, preserve unreachable pairs, and detect negative cycles with eight runnable Smalltalk checkpoints.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Open a fresh Workspace in Squeak. Select one complete checkpoint and choose Print it. Each checkpoint declares and initializes its own data, so you can run them in any order. Vertices A, B, C, D use indices 1 through 4. Costs are abstract signed numbers, not geographic distances. The downloadable Morphic board shows the direct-edge table followed by the four computed phases.

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.

Expected values are Smalltalk expressions. The printer may show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.

01 - Build a directed distance matrix

Rows are starting vertices and columns are destinations, ordered A, B, C, D. A number is the cost of a direct edge; nil means no known route. Zero on the diagonal permits the empty route. The B → C edge costs −2, but the B → C → D → B cycle costs 3, not a negative number. Unlike Dijkstra or Bellman–Ford from one source, our goal is a distance for every ordered pair.

Independent Workspace expression - select all, then Print it
| distance |
distance := {{0. 3. nil. 10}. {nil. 0. -2. nil}.
 {nil. nil. 0. 4}. {nil. 1. nil. 0}}.
{((distance at: 1) at: 2). ((distance at: 2) at: 1).
 ((distance at: 2) at: 3) + ((distance at: 3) at: 4) + ((distance at: 4) at: 2)}

Expected: {3. nil. 3}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Build a directed distance matrix
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Read the table in reverse: B cannot reach A. Directed edges are not automatically symmetric.

Download this checkpoint

02 - Allow one intermediate vertex

Floyd–Warshall asks whether going from i to k and then k to j beats the old i-to-j distance. Both halves must exist before we add them. Here only B is allowed as an intermediate: A → B → C costs 1, and D → B → C costs −1. Copy each row, not just the outer array, so this checkpoint reads a stable previous phase.

Independent Workspace expression - select all, then Print it
| distance previous k |
distance := {{0. 3. nil. 10}. {nil. 0. -2. nil}.
 {nil. nil. 0. 4}. {nil. 1. nil. 0}}.
k := 2.
previous := distance collect: [:row | row copy].
1 to: 4 do: [:i |
 1 to: 4 do: [:j | | left right old candidate |
  left := (previous at: i) at: k.
  right := (previous at: k) at: j.
  old := (previous at: i) at: j.
  (left notNil and: [right notNil]) ifTrue: [
   candidate := left + right.
   (old isNil or: [candidate < old]) ifTrue: [
    (distance at: i) at: j put: candidate]]]].
{(distance at: 1) at: 3. (distance at: 4) at: 3}

Expected: #(1 -1)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Allow one intermediate vertex
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Why is A → D still 10? This phase has not allowed C as an intermediate.

Download this checkpoint

03 - Run all four dynamic-programming phases

Keep k as the outer loop. After phase k, entries describe shortest routes whose intermediate vertices belong to the first k vertices, assuming there is no negative cycle. Endpoints may be anywhere. Each phase reads the previous matrix and improves the working matrix. The final table includes C → B = 5 via D, and A → D = 5 via B and C.

Independent Workspace expression - select all, then Print it
| distance previous |
distance := {{0. 3. nil. 10}. {nil. 0. -2. nil}.
 {nil. nil. 0. 4}. {nil. 1. nil. 0}}.
1 to: 4 do: [:k |
 previous := distance collect: [:row | row copy].
 1 to: 4 do: [:i |
  1 to: 4 do: [:j | | left right old candidate |
   left := (previous at: i) at: k.
   right := (previous at: k) at: j.
   old := (previous at: i) at: j.
   (left notNil and: [right notNil]) ifTrue: [
    candidate := left + right.
    (old isNil or: [candidate < old]) ifTrue: [
     (distance at: i) at: j put: candidate]]]]].
distance

Expected: {{0. 3. 1. 5}. {nil. 0. -2. 2}. {nil. 5. 0. 4}. {nil. 1. -1. 0}}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Run all four dynamic-programming phases
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Check A → D: 3 + (−2) + 4 = 5. Find which final phase first discovers C → B.

Download this checkpoint

04 - Ask several queries without rerunning the algorithm

The cubic computation is useful when you need many source–destination questions on the same small graph. Once computed, each matrix lookup is constant time. The negative answer for D → C is a legitimate finite cost. A nil answer means unreachable, not zero and not an error.

Independent Workspace expression - select all, then Print it
| distance previous |
distance := {{0. 3. nil. 10}. {nil. 0. -2. nil}.
 {nil. nil. 0. 4}. {nil. 1. nil. 0}}.
1 to: 4 do: [:k |
 previous := distance collect: [:row | row copy].
 1 to: 4 do: [:i |
  1 to: 4 do: [:j | | left right old candidate |
   left := (previous at: i) at: k.
   right := (previous at: k) at: j.
   old := (previous at: i) at: j.
   (left notNil and: [right notNil]) ifTrue: [
    candidate := left + right.
    (old isNil or: [candidate < old]) ifTrue: [
     (distance at: i) at: j put: candidate]]]]].
{(distance at: 1) at: 4. (distance at: 4) at: 3.
 (distance at: 3) at: 1. (distance at: 2) at: 2}

Expected: {5. -1. nil. 0}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Ask several queries without rerunning the algorithm
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Change the first query to C → B. The result is 5, even though no direct C → B edge exists.

Download this checkpoint

05 - Remember how to reconstruct a route

A distance does not tell us the route. Add a next-hop table: a direct route to j starts by going to j. When i → k → j improves an entry, its first hop is the first hop on the previous i → k route. Snapshot both tables. This example reconstructs the known reachable A → D route; a general query must first reject nil and any relevant negative cycle before following pointers.

Independent Workspace expression - select all, then Print it
| distance previous nextHop oldNext route current |
distance := {{0. 3. nil. 10}. {nil. 0. -2. nil}.
 {nil. nil. 0. 4}. {nil. 1. nil. 0}}.
nextHop := (1 to: 4) collect: [:i |
 (1 to: 4) collect: [:j |
  ((distance at: i) at: j) ifNotNil: [j]]].
1 to: 4 do: [:k |
 previous := distance collect: [:row | row copy].
 oldNext := nextHop collect: [:row | row copy].
 1 to: 4 do: [:i |
  1 to: 4 do: [:j | | left right old candidate |
   left := (previous at: i) at: k.
   right := (previous at: k) at: j.
   old := (previous at: i) at: j.
   (left notNil and: [right notNil]) ifTrue: [
    candidate := left + right.
    (old isNil or: [candidate < old]) ifTrue: [
     (distance at: i) at: j put: candidate .
     (nextHop at: i) at: j put: ((oldNext at: i) at: k)]]]]].
route := OrderedCollection with: 1.
current := 1.
[current ~= 4] whileTrue: [
 current := (nextHop at: current) at: 4.
 route add: current].
route asArray

Expected: #(1 2 3 4)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Remember how to reconstruct a route
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Translate the indices to A, B, C, D. Sum the original edges, not arbitrary entries in the completed matrix, to check the cost is 5.

Download this checkpoint

06 - Detect a negative cycle before trusting distances

A negative edge is allowed; a negative cycle is different. In this three-vertex graph the cycle costs 1 − 3 + 1 = −1, so repeated trips reduce the cost forever. After relaxation, any negative diagonal detects that a negative cycle exists. Only pairs that can reach such a cycle and then reach their destination lack a finite shortest distance. Do not present the affected table entries as shortest paths or follow route pointers indefinitely.

Independent Workspace expression - select all, then Print it
| distance previous |
distance := {{0. 1. nil}. {nil. 0. -3}. {1. nil. 0}}.
1 to: 3 do: [:k |
 previous := distance collect: [:row | row copy].
 1 to: 3 do: [:i |
  1 to: 3 do: [:j | | left right old candidate |
   left := (previous at: i) at: k.
   right := (previous at: k) at: j.
   old := (previous at: i) at: j.
   (left notNil and: [right notNil]) ifTrue: [
    candidate := left + right.
    (old isNil or: [candidate < old]) ifTrue: [
     (distance at: i) at: j put: candidate]]]]].
(1 to: 3) anySatisfy: [:vertex | ((distance at: vertex) at: vertex) < 0]

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Detect a negative cycle before trusting distances
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Change −3 to −1. The cycle then costs 1; the negative-diagonal test should answer false.

Download this checkpoint

07 - Keep disconnected vertices disconnected

The nil guard is part of the algorithm, not just display formatting. This graph has an isolated C. Even after every phase there is no A → C or C → A route, while C → C is zero for the empty route. Artificially using zero for missing edges would invent free connections.

Independent Workspace expression - select all, then Print it
| distance previous |
distance := {{0. 7. nil}. {nil. 0. nil}. {nil. nil. 0}}.
1 to: 3 do: [:k |
 previous := distance collect: [:row | row copy].
 1 to: 3 do: [:i |
  1 to: 3 do: [:j | | left right old candidate |
   left := (previous at: i) at: k.
   right := (previous at: k) at: j.
   old := (previous at: i) at: j.
   (left notNil and: [right notNil]) ifTrue: [
    candidate := left + right.
    (old isNil or: [candidate < old]) ifTrue: [
     (distance at: i) at: j put: candidate]]]]].
{(distance at: 1) at: 3. (distance at: 3) at: 1. (distance at: 3) at: 3}

Expected: {nil. nil. 0}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Keep disconnected vertices disconnected
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Add an edge B → C of cost 2 before the loops. A → C should become 9, while C → A remains nil.

Download this checkpoint

08 - Check the completed table against every possible detour

A useful postcondition is closure: no reachable two-part detour through any k should improve a completed entry. This tests all 64 triples independently against the final table. It is not a complete proof by itself: a wrongly low table could also pass. Combine it with known routes, unreachable-pair checks and the negative-cycle test. Four phases of sixteen pairs make 64 relaxation attempts; in general the algorithm takes O(n³) time and O(n²) live storage, including one snapshot.

Independent Workspace expression - select all, then Print it
| distance previous violations |
distance := {{0. 3. nil. 10}. {nil. 0. -2. nil}.
 {nil. nil. 0. 4}. {nil. 1. nil. 0}}.
1 to: 4 do: [:k |
 previous := distance collect: [:row | row copy].
 1 to: 4 do: [:i |
  1 to: 4 do: [:j | | left right old candidate |
   left := (previous at: i) at: k.
   right := (previous at: k) at: j.
   old := (previous at: i) at: j.
   (left notNil and: [right notNil]) ifTrue: [
    candidate := left + right.
    (old isNil or: [candidate < old]) ifTrue: [
     (distance at: i) at: j put: candidate]]]]].
violations := 0.
1 to: 4 do: [:i |
 1 to: 4 do: [:j |
  1 to: 4 do: [:k | | left right direct |
   left := (distance at: i) at: k.
   right := (distance at: k) at: j.
   direct := (distance at: i) at: j.
   (left notNil and: [right notNil]) ifTrue: [
    (direct isNil or: [direct > (left + right)]) ifTrue: [
     violations := violations + 1]]]]].
violations

Expected: 0

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Check the completed table against every possible detour
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try checking the initial direct-edge matrix instead. It must fail closure because A → B → C improves an unknown A → C entry.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Floyd–Warshall in Squeak: Shortest Paths Between Every Pair 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

Keep the intermediate-vertex loop outermost; one arbitrary ordering of the three loops is not the same dynamic program.

Copy every row for a phase snapshot. Copying only the outer array leaves shared mutable rows.

Never add nil to a number. Missing edges are not zero-cost edges.

For parallel directed edges, initialize with the minimum edge cost. Preserve a negative self-loop instead of overwriting it with zero.

A negative diagonal signals a negative cycle. Affected source–destination pairs have no finite optimum; path reconstruction must reject them.

The route-following checkpoint assumes the supplied reachable, negative-cycle-free graph. Production code should handle unreachable queries and impose a defensive hop limit.

Use Floyd–Warshall for small or dense graphs and many queries. For large sparse graphs, compare repeated single-source methods rather than allocating a dense matrix blindly.

Three practice challenges

Make the graph undirected

Mirror every direct edge before relaxing. What happens to the B–C edge of cost −2?

Show solution

Mirroring creates B → C → B with cost −4. A negative undirected edge therefore makes an immediate negative cycle under this walk model. Use nonnegative weights for this undirected experiment and verify the final table is symmetric.

Add a cheaper direct shortcut

Change A → D from 10 to 4. Predict A → D and the reconstructed route. Does D → A change?

Show solution

A → D becomes 4 and the next-hop route is #(1 4). D → A stays nil because no edge reaches A. Only strictly better candidates replace a route, so an equal-cost alternative need not replace the existing one.

Compare single-source and all-pairs costs

Why not always replace Dijkstra or Bellman–Ford with this matrix? What costs grow when the number of vertices doubles?

Show solution

Floyd–Warshall computes answers for every pair whether needed or not. Doubling n multiplies the cubic relaxation work by eight and matrix storage by four. Single-source methods avoid that full table when only one source is needed; Dijkstra additionally requires nonnegative edge weights, whereas Bellman–Ford handles negative edges and detects reachable negative cycles.

Continue learning

Dijkstra Shortest Paths | Bellman Ford | Matrix Power | Collections

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