s LearnSqueak.com

SMALLTALK LAB

Dijkstra: find the cheapest route through a weighted graph

Separate cheapest from fewest hops, improve tentative distances, settle the minimum, and reconstruct a route with exact integer costs and native computed snapshots.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use Squeak 6.1 with Arrays, OrderedCollection, blocks and nil. Open a Workspace, paste one entire step including its temporary declaration, select all and choose Print it. Each step is independent and needs no installed classes. Unlike the existing unit-cost grid BFS/A* lesson, this lesson uses an arbitrary directed graph with unequal nonnegative integer edge costs. Number vertices from 1 through count; represent each edge as a three-item Array.

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 - Describe directed edges with costs

Vertices 1 through 5 stand for A through E. Each triple is source, destination, cost. An edge only works in its listed direction. The direct A-to-B trip costs 7, but A-to-C-to-B costs just 3: fewest edges is not the same as lowest cost.

Independent Workspace expression - select all, then Print it
| edges |
edges := #((1 2 7) (1 3 2) (3 2 1) (3 4 8) (2 4 2)).
{edges first. (edges second third) + (edges third third)}

Expected: {#(1 2 7). 3.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Describe directed edges with costs
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Vertex E has no edges. We retain it so an unreachable result remains visible.

Download this checkpoint

02 - Require nonnegative integer weights

Dijkstra settles a minimum distance permanently. Nonnegative costs make that safe: extending a route cannot make it cheaper. We choose integer costs for exact arithmetic; zero is allowed. This small predicate previews the validation in the complete solver.

Independent Workspace expression - select all, then Print it
| validCost |
validCost := [:cost | cost isInteger and: [cost >= 0]].
{validCost value: 0. validCost value: 7.
 validCost value: -1. validCost value: 1.5}

Expected: #(true true false false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Require nonnegative integer weights
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: A negative edge is not merely an unusual input: it invalidates the settling argument. Use an algorithm designed for it, such as Bellman-Ford.

Download this checkpoint

03 - Keep unknown distance separate from zero

A nil slot means no route has yet been discovered. Zero is a real distance, including the empty route from A to itself. There is no guessed large number standing in for infinity.

Independent Workspace expression - select all, then Print it
| distances previous settled |
distances := Array new: 5. previous := Array new: 5.
settled := Array new: 5 withAll: false.
distances at: 1 put: 0.
{distances. previous. settled}

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

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Keep unknown distance separate from zero
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: An undiscovered vertex is not the same as an unreachable vertex until the algorithm finishes.

Download this checkpoint

04 - Relax an edge and replace its predecessor

After settling C at cost 2, its cost-1 edge offers B a cheaper route than the previous cost 7. Relaxation changes the distance and predecessor together. A predecessor records the previous vertex, not a cost.

Independent Workspace expression - select all, then Print it
| distances previous candidate old |
distances := #(0 7 2 nil nil) copy.
previous := #(nil 1 1 nil nil) copy.
candidate := (distances at: 3) + 1. old := distances at: 2.
(old isNil or: [candidate < old]) ifTrue: [
 distances at: 2 put: candidate. previous at: 2 put: 3].
{distances at: 2. previous at: 2}

Expected: #(3 3)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Relax an edge and replace its predecessor
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Only a strictly smaller distance replaces a predecessor. Equal alternatives retain the first route found.

Download this checkpoint

05 - Select the cheapest unsettled vertex

A and C are already settled. B has tentative cost 3, D has 10, and E is unknown. Scan known unsettled vertices and select B. Iterating indexes in ascending order makes equal-distance choices deterministic.

Independent Workspace expression - select all, then Print it
| distances settled current |
distances := #(0 3 2 10 nil). settled := #(true false true false false).
current := nil.
1 to: 5 do: [:v |
 ((settled at: v) not and: [(distances at: v) notNil]) ifTrue: [
  (current isNil or: [(distances at: v) < (distances at: current)])
   ifTrue: [current := v]]].
current

Expected: 2

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Select the cheapest unsettled vertex
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The or: block avoids comparing with nil. Do not select vertices just because they were discovered first.

Download this checkpoint

06 - Run until no reachable candidate remains

Build a separate outgoing list for each vertex, then repeat minimum selection, settling and relaxation. The result contains distances, predecessor indexes and settlement order. No route reaches E, so its distance remains nil. Input data is read, not mutated.

Independent Workspace expression - select all, then Print it
| shortest |
shortest := [:count :edges :start | | adjacency distances previous settled order current candidate old |
 (count isInteger and: [count > 0])
  ifFalse: [Error signal: 'Use a positive vertex count'].
 (start isInteger and: [start between: 1 and: count])
  ifFalse: [Error signal: 'Start is outside the graph'].
 adjacency := (1 to: count) collect: [:i | OrderedCollection new].
 edges do: [:edge |
  edge size = 3 ifFalse: [Error signal: 'Use source, destination, cost triples'].
  (edge first isInteger and: [edge first between: 1 and: count])
   ifFalse: [Error signal: 'Invalid source'].
  (edge second isInteger and: [edge second between: 1 and: count])
   ifFalse: [Error signal: 'Invalid destination'].
  (edge third isInteger and: [edge third >= 0])
   ifFalse: [Error signal: 'Use nonnegative integer costs'].
  (adjacency at: edge first) add: {edge second. edge third}].
 distances := Array new: count. previous := Array new: count.
 settled := Array new: count withAll: false. order := OrderedCollection new.
 distances at: start put: 0.
 [current := nil.
  1 to: count do: [:v |
   ((settled at: v) not and: [(distances at: v) notNil]) ifTrue: [
    (current isNil or: [(distances at: v) < (distances at: current)])
     ifTrue: [current := v]]].
  current notNil] whileTrue: [
   settled at: current put: true. order add: current.
   (adjacency at: current) do: [:edge |
    (settled at: edge first) ifFalse: [
     candidate := (distances at: current) + edge second.
     old := distances at: edge first.
     (old isNil or: [candidate < old]) ifTrue: [
      distances at: edge first put: candidate.
      previous at: edge first put: current]]]].
 {distances. previous. order asArray}].
shortest value: 5 value: #((1 2 7) (1 3 2) (3 2 1) (3 4 8) (2 4 2)) value: 1

Expected: #(#(0 3 2 5 nil) #(nil 3 1 2 nil) #(1 3 2 4))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Run until no reachable candidate remains
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: D is discovered at cost 10 before improving to 5. A discovered target is not necessarily finished; only its selection as the minimum makes its distance final.

Download this checkpoint

07 - Recover a route by walking backward

Use the predecessor array from the actual solve, starting at D. Prepend each visited vertex until nil marks the source. Check reachability first: an unreachable target has no route, whereas source-to-source has a one-vertex route.

Independent Workspace expression - select all, then Print it
| shortest result route vertex |
shortest := [:count :edges :start | | adjacency distances previous settled order current candidate old |
 (count isInteger and: [count > 0])
  ifFalse: [Error signal: 'Use a positive vertex count'].
 (start isInteger and: [start between: 1 and: count])
  ifFalse: [Error signal: 'Start is outside the graph'].
 adjacency := (1 to: count) collect: [:i | OrderedCollection new].
 edges do: [:edge |
  edge size = 3 ifFalse: [Error signal: 'Use source, destination, cost triples'].
  (edge first isInteger and: [edge first between: 1 and: count])
   ifFalse: [Error signal: 'Invalid source'].
  (edge second isInteger and: [edge second between: 1 and: count])
   ifFalse: [Error signal: 'Invalid destination'].
  (edge third isInteger and: [edge third >= 0])
   ifFalse: [Error signal: 'Use nonnegative integer costs'].
  (adjacency at: edge first) add: {edge second. edge third}].
 distances := Array new: count. previous := Array new: count.
 settled := Array new: count withAll: false. order := OrderedCollection new.
 distances at: start put: 0.
 [current := nil.
  1 to: count do: [:v |
   ((settled at: v) not and: [(distances at: v) notNil]) ifTrue: [
    (current isNil or: [(distances at: v) < (distances at: current)])
     ifTrue: [current := v]]].
  current notNil] whileTrue: [
   settled at: current put: true. order add: current.
   (adjacency at: current) do: [:edge |
    (settled at: edge first) ifFalse: [
     candidate := (distances at: current) + edge second.
     old := distances at: edge first.
     (old isNil or: [candidate < old]) ifTrue: [
      distances at: edge first put: candidate.
      previous at: edge first put: current]]]].
 {distances. previous. order asArray}].
result := shortest value: 5 value: #((1 2 7) (1 3 2) (3 2 1) (3 4 8) (2 4 2)) value: 1.
route := OrderedCollection new. vertex := 4.
(result first at: vertex) notNil ifTrue: [
 [vertex notNil] whileTrue: [
  route addFirst: vertex. vertex := result second at: vertex]].
{route asArray. result first at: 4}

Expected: #(#(1 3 2 4) 5)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Recover a route by walking backward
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Add the route costs: A to C is 2, C to B is 1, B to D is 2. The total is 5 despite using three edges instead of two.

Download this checkpoint

08 - Test zero costs, isolation and rejected input

Zero-cost edges and cycles are allowed. Settling each vertex once and updating only on strict improvement prevent predecessor cycles. A singleton source has distance zero. Finally, catch the intentional negative-weight error so this entire example remains evaluable.

Independent Workspace expression - select all, then Print it
| shortest zero isolated rejected |
shortest := [:count :edges :start | | adjacency distances previous settled order current candidate old |
 (count isInteger and: [count > 0])
  ifFalse: [Error signal: 'Use a positive vertex count'].
 (start isInteger and: [start between: 1 and: count])
  ifFalse: [Error signal: 'Start is outside the graph'].
 adjacency := (1 to: count) collect: [:i | OrderedCollection new].
 edges do: [:edge |
  edge size = 3 ifFalse: [Error signal: 'Use source, destination, cost triples'].
  (edge first isInteger and: [edge first between: 1 and: count])
   ifFalse: [Error signal: 'Invalid source'].
  (edge second isInteger and: [edge second between: 1 and: count])
   ifFalse: [Error signal: 'Invalid destination'].
  (edge third isInteger and: [edge third >= 0])
   ifFalse: [Error signal: 'Use nonnegative integer costs'].
  (adjacency at: edge first) add: {edge second. edge third}].
 distances := Array new: count. previous := Array new: count.
 settled := Array new: count withAll: false. order := OrderedCollection new.
 distances at: start put: 0.
 [current := nil.
  1 to: count do: [:v |
   ((settled at: v) not and: [(distances at: v) notNil]) ifTrue: [
    (current isNil or: [(distances at: v) < (distances at: current)])
     ifTrue: [current := v]]].
  current notNil] whileTrue: [
   settled at: current put: true. order add: current.
   (adjacency at: current) do: [:edge |
    (settled at: edge first) ifFalse: [
     candidate := (distances at: current) + edge second.
     old := distances at: edge first.
     (old isNil or: [candidate < old]) ifTrue: [
      distances at: edge first put: candidate.
      previous at: edge first put: current]]]].
 {distances. previous. order asArray}].
zero := shortest value: 3 value: #((1 2 0) (2 1 0) (2 3 4)) value: 1.
isolated := shortest value: 1 value: #() value: 1.
rejected := [shortest value: 2 value: #((1 2 -1)) value: 1. false]
 on: Error do: [:error | error messageText = 'Use nonnegative integer costs'].
{zero first = #(0 0 4). isolated first = #(0). rejected}

Expected: #(true true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Test zero costs, isolation and rejected input
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try starting the main fixture at E. Its own distance is zero and the other four distances remain nil.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Dijkstra: find the cheapest route through a weighted graph 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

The minimum scan costs O(V) per settled vertex. Building outgoing lists takes O(V + E), and processing edges totals O(E), so this version takes O(V squared + E) time and O(V + E) storage. A suitable priority queue can improve sparse-graph performance; this lesson deliberately uses an inspectable scan.

Dijkstra needs nonnegative edge costs. Integer costs here avoid Float rounding and infinity sentinels. This solver validates endpoints and integer costs but assumes each edge is an indexable triple. It is an educational in-memory graph interface, not an untrusted-data parser.

Do not mark vertices settled on first discovery. B is discovered at 7 and later improved to 3. For a single-target variant, stop only when that target is selected as the cheapest unsettled vertex.

Directed edges are not automatically reversible. To model an undirected connection, supply both directions. Parallel edges and self-loops are allowed; strict improvement and the settled flag keep predecessor chains finite.

Three practice challenges

Challenge 1: make a direct route win

Change A-to-B from 7 to 1. What should happen to the route and cost to D?

Show solution

B settles before C. Its outgoing edge gives D a distance of 3 and route #(1 2 4). C remains at distance 2, and E remains unreachable.

Challenge 2: describe an unreachable target

Use target 5 in the reconstruction step. What does the block return, and why is source-to-source different?

Show solution

It returns an empty route and nil cost: {#(). nil}. Target 1 returns route #(1) and cost 0. The reachability guard distinguishes absence from a valid zero-edge route.

Challenge 3: equal costs without route churn

Add edge #(1 4 5) to the original fixture. Which predecessor does D keep, and is the answer still optimal?

Show solution

D first receives cost 5 directly from A. The later route through B also costs 5, so strict < retains predecessor 1. Both routes are optimal; this implementation promises a minimum cost, not the most edges, fewest edges, or every optimal route.

Continue learning

Pathfinding | Priority Queue | Collections

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