The st-Gilbert (v5_stable) Algorithm
Constructing Hilbert-like space-filling curves between arbitrary endpoints on any 2D integer grid
The st-Gilbert (v5_stable) algorithm
constructs a Hamiltonian path between any acceptable pair of endpoints
on any 2D integer grid, with formally proved bounds on straight runs,
turn density, and Euclidean dilation. Each section gives a conceptual
overview illustrated by figures, followed by an Implementation
Details box containing exact thresholds, cut formulas, and
identifiers from the Lean 4 specification (lean/StGilbert/)
and reference implementations (ref/).
All figures showing real curves are generated from
ref/c/stgfull by gen_figures.py with exact sub-box
boundaries and junction crossings overlaid.
1. Overview & Architecture
Goal and Space-Filling Properties
The goal is to construct an arbitrary-endpoint analogue of the 2D Hilbert curve: a Hamiltonian path on any integer grid from start cell to end cell (visiting every cell once via unit horizontal and vertical steps) that also functions as a discrete space-filling curve with four properties (defined formally with proved bounds in Section 9):
- Spatial locality (bounded dilation): Cells that are close along the 1D curve remain close in 2D Euclidean distance; every contiguous segment of length stays within a diameter of on bounded-aspect rectangles.
- Short straight runs and high turn density: The curve turns frequently (75%–80% of moves on typical grids, near the 2D Hilbert curve’s 75%), keeping both maximum and average straight-run lengths small.
- Exact 2D Hilbert identity: On every power-of-two square () with endpoints and , the output is identical to the classic 2D Hilbert curve.
- Localized endpoint disruption and stability: Routing around interior endpoints stays confined to a small sub-region around and , leaving the bulk of the grid Hilbert-like and keeping most edges unchanged under small shifts of size or endpoints.
Existence Criterion
Colour the grid like a checkerboard: cell is dark when is even and light when is odd. Because every unit step alternates colours, a Hamiltonian path from to requires colour compatibility:
- Odd total area ( odd): dark cells outnumber light cells by one, so both and must be dark (the colour of ).
- Even total area ( even): dark and light cells are equal, so and must have opposite colours.
For all grids with and , colour compatibility is both necessary and sufficient. For grids with , Itai, Papadimitriou, and Szwarcfiter (1982; IPS) showed that a finite family of thin-strip separation obstructions must also be excluded.
The Four Building-Block Job Types
The algorithm recursively partitions a rectangle into well-shaped sub-rectangles so that almost the entire grid becomes simple corner-to-corner Hilbert-like blocks. Every recursive call in the core solver is one of four job types:
- Corner job (blue) — both endpoints lie within Manhattan distance 1 of two distinct corners. This is the Hilbert workhorse that fills the bulk of the grid.
- One-interior job (green) — one endpoint lies within distance 1 of a corner; the other lies anywhere inside.
- Two-interior job (indigo) — both endpoints lie anywhere inside.
- Two-path job (amber) — an even-area box covered by two disjoint paths connecting the two endpoints to two border ports near opposite corners.
Ports and Free Pairing
When both endpoints and sit close together in one corner of a box, isolating them inside a corner quadrant allows the outer L-shaped 3/4 of the box to be filled by two Corner jobs ( and ). The complete path starts at inside , exits through a border cell (port A or port B), traverses the outer bridge , re-enters through the other port, and finishes at .
Because the outer bridge is an undirected Hamiltonian path between the cells adjacent to port A and port B, it can be traversed in either direction. The two-path solver is therefore free to choose whichever endpoint-to-port pairing succeeds and return a boolean pairing flag:
flag = false( and ): the caller glues the outer bridge forward, yielding .flag = true( and ): the caller glues the outer bridge in reverse, yielding .
Allowing free pairing eliminates the crossing obstructions of general Zig-Zag Numberlink, leaving a small closed set of geometric rules proved complete in Lean.
The Three Universal Moves
Every decomposition in the core layers is one of three geometric moves:
- Separate (
sep): Cut straight across the box with and on opposite sides.- In a 1-path job, the path crosses the cut once at a corner junction, producing two simpler 1-path jobs.
- In a 2-path job, zero edges cross the cut: each half already holds one endpoint and one port, so the 2-path recursion terminates directly into two independent 1-path jobs and fixes the pairing flag.
- Zoom (
zoom): Fence clustered endpoints inside an even-area corner quadrant as a 2-path job, covering the remaining 3/4 of the box with two Corner jobs. - Peel (
peel): Inside a 2-path job where both endpoints lie on the same side of a cut, slice off the empty even-area side (holding one port) as a Corner job, shift that port inward onto the cut line with the same checkerboard colour, and recurse on the smaller 2-path box untilsepseparates the endpoints.
2. Top-Level Dispatch, Shared Conventions & Parity
Section Overview
This section defines the top-level dispatch of
stgFull(B, s, t) across four grid-shape regimes, the three
geometric conventions shared by all core layers, and how odd-area boxes
and corner proximity are handled uniformly across the recursion.
Four Shape Regimes
The entry point stgFull(B, s, t) partitions all grid
shapes by short side
and aspect ratio
:
- Thin strips
():
Solved by the constructive IPS solver (
ipsBox, Section 8). Thin strips can force straight runs equal to the strip length, so constant run bounds apply only for . - Near-square
(,
):
Solved by the core recursive rules (Sections 3–5). For
,
these rules are proved complete with zero fallback; for
,
any state where the two-interior rules return empty falls back to
ipsBox. - Long and thick
(,
):
Solved by
longPath(Section 6), which decomposes the elongated box into near-square pieces of aspect handled by the core rules. - Long and narrow
(,
):
Solved by
narrowPath(Section 7), which solves a core block around and and splices tiled Hilbert-like excursions onto the empty ends.
stgFull(B, s, t)
├── min(w, h) <= 3 ─────────────────────────────► ipsBox(B, s, t) [Section 8]
└── min(w, h) >= 4
├── aspect <= 9/4 (4w <= 9h and 4h <= 9w) ──► stgPath(B, s, t)
│ ├── Both ends near corners ────────────► Corner job [Section 3]
│ ├── One end near a corner ─────────────► One-interior job [Section 4]
│ ├── Both ends interior ────────────────► Two-interior job [Section 5]
│ └── Fallback (only possible if min<20) ► ipsBox(B, s, t) [Section 8]
├── aspect > 9/4 and min(w, h) >= 20 ───────► longPath(B, s, t) [Section 6]
└── aspect > 9/4 and 4 <= min(w, h) <= 19 ──► narrowPath(B, s, t) [Section 7]
Three Shared Conventions
- Well-shaped sub-boxes (
ShapeOK): Every recursive piece in Sections 3–5 satisfies and . Keeping all pieces well-shaped bounds both straight runs and Euclidean dilation. - Parity-matching junctions (
pickC/flipK): Every cut crossing near a corner selects between the corner cell itself and its adjacent border neighbour along the cut (distance from the corner). Because these two adjacent cells have opposite checkerboard colours, one always matches the colour required by the sub-box. - Centered middle-out cuts (
midOut) and canonical frames (ffr/fto): Cut candidates are ordered outward from the midpoint () inside the middle third . Rules are defined once in a canonical origin box by transforming the box in (ffr) and mapping the resulting path back out (fto).
Parity of Cut Sub-Boxes and Endpoint Classification
- Odd-area and even-area boxes: Every acceptable input grid — odd or even — is solved directly. Two-path boxes (Z and W) and peeled outer slices always have even area because the algorithm chooses an even cut coordinate or when creating them. On an odd-area parent box ( and both odd), cutting an even quadrant leaves the oddness in one outer 1-path Corner box, where odd area is handled directly by choosing an even cut along the opposite axis. Requiring even area on two-path boxes and peeled slices guarantees that every peeled Corner box works for both port colours, enabling colour-blind peeling (Section 4).
- Corner proximity as recursion progress: Endpoint proximity to corners (Manhattan distance ) classifies every near-square job into one of three tiers: 2 corner ends (Corner job), 1 corner end (One-interior job), or 0 corner ends (Two-interior job). Every cut places its new crossing junction within distance 1 of a corner of each child box, strictly reducing the count of interior endpoints ().
3. Corner Jobs (stPath)
Section Overview
Corner jobs cover any well-shaped box (ShapeOK) with
endpoints
within distance 1 of two distinct corners. After normalizing orientation
(,
on the left edge, and
at bottom-left if both ends are on the left), boxes with
return a stored Hilbert-like leaf path from tab1. Larger
boxes
()
apply one of three cuts into smaller well-shaped Corner jobs, rounding
the cut to an even integer whenever the perpendicular side is odd so
every child remains colour-compatible.
The Three Control Paths
- Near-square U-turn (Rule 3, panels a & b): Applies when both ends lie on the same edge (bottom, top, or left) and . Splits into three Corner boxes forming a Hilbert U-turn: two lower boxes flanking a full-span opposite half . Ends on the left edge apply this rule in the transposed frame; ends on the top edge mirror vertically first.
- Vertical bisection (Rule 1, panel c): Applies when the ends lie on opposite sides (left and right) and Rule 3 is inactive (either or the ends sit at diagonally opposite corners). Splits vertically near and crosses once near the bottom of the cut.
- Elongated strip U-turn (Rule 2b, panel d): Applies
when both ends lie on the same short side (left edge) and
.
Slices off an even-width left strip carrying two paths
(
exiting at bottom-right,
entering at top-right), joined across two junctions to one Corner job on
the right remainder. Strips with both sides
use stored two-path table
tab2; larger strips split horizontally at into two Corner jobs.
Exact 2D Hilbert Recursion
On every
square
()
with endpoints
and
,
Rule 3 cuts at
and
,
producing two lower
quadrants
and one top rectangle
of size
.
Because
has aspect ratio
with endpoints at its bottom corners, the next recursive call
immediately applies Rule 1 to bisect
vertically into the two upper quadrants
.
Together with exact Hilbert
and
leaves in tab1, this produces the exact 2D Hilbert curve
for all
.
Implementation Details (Section 3 —
Corner.lean): - InvariantInv1(B, a, b):ShapeOK(B),Compat(B, a, b), within Manhattan distance of two distinct corners (NearC). - Normalization: Transpose if ; lookuptab1if ; mirror left-right (refl) if both ends have ; swap and reverse output if¬First(B, a, b). - Cut formulas: - Rule 1:cut1(w, h), minus if odd and odd. - Rule 3:r3h(h); bottom widths and . - Rule 2b:cs2b(w, h). (A legacyOk2a/case2abranch remains in code for proof continuity, though implies , so transposedcase3handles everyOk2a-eligible box first.) - Junction parity: Each crossing cell is offset byflipK(q, p) ∈ {0, 1}along the cut so the first child’s endpoint has colour opposite to (or ).
4. One Interior
Endpoint (onePath: S and Z Jobs)
Section Overview
One-interior jobs cover a well-shaped box where endpoint lies within distance 1 of a corner and endpoint lies anywhere inside. When also lies within distance 1 of another corner, the box delegates immediately to a Corner job (Section 3). Otherwise, the box is framed with near in and solved by mutual recursion between one-path S jobs and two-path Z jobs. S jobs prioritize 1-path reductions (L-split on near-squares, Separate on elongated boxes) and fall back to Zoom into an even-area Z quadrant when lies near ’s corner; Z jobs repeatedly Peel empty even sides as Corner jobs until a straight cut separates from .
Part A: One-Path S Jobs ()
Small boxes
(,
or
and
)
return a stored path from tabG. Larger boxes try four moves
in both the base frame and its transpose, taking the first valid
middle-third cut:
- L-split (
lsplit, panel a — first on near-squares ): Partitions into three well-shaped pieces: two Corner jobs ( bottom-left, full-height right) plus a smaller one-interior job in the top-left containing , preserving a Hilbert U-turn across 3/4 of the box. - Separate (
sep, panel b — first on elongated boxes ): Cuts vertically between and into a Corner job (holding ) and a smaller one-interior job (holding ), crossing once near either end of the cut. - Zoom into Z (
zoom, panel c): When lies in the bottom-left quadrant (off its 4 inner port cells), selects an even-area quadrant for a two-path Z job and covers the outer right and top-left boxes with Corner jobs . When is even, both and are even; when is odd, one outer Corner box absorbs the oddness. - Thin-box U-turn (
uturn, panel d): Slices off an even leaf strip holding and (solved by stored 2-path tabletabZs) and attaches a Corner job on the right.
A final fallback widens sep to the middle half of the
side if all middle-third cuts are blocked.
Part B: Two-Path Z Jobs (Inside an S Zoom)
An S zoom passes its even-area quadrant
(transposed if needed so
)
to a Z job with
near
,
inside, and two border ports:
(right edge near bottom-right) and
(top edge near top-left). As shown in Ports and Free Pairing, Z returns two
disjoint paths
and a pairing flag: - flag = false (H
pairing):
and
(outer bridge
glued forward). - flag = true (V
pairing):
and
(outer bridge glued in reverse).
Small boxes (zLeaf) look up tabZo. Larger
boxes take the first valid middle-third cut from five rules:
- Terminating separations (zero crossings on the
cut):
- Horizontal separate (
hsplit): Cuts horizontally below (bottom even). Bottom becomes a Corner job (); top becomes a one-interior job (). Returnsflag = false. - Vertical separate (
vsplit): Cuts vertically left of (left even). Left becomes a Corner job (); right becomes a one-interior job (). Returnsflag = true.
- Horizontal separate (
- Shrinking peels (empty even sides solved as Corner
jobs):
- Double peel (
Z zoom): Peels both the right box and top-left box as Corner jobs simultaneously, recursing Z on the smaller quadrant. - Right peel (
vpeel): Peels the empty even right side as Corner job , shifts port left onto the cut line with the same colour, and recurses Z on the left box. - Top peel (
hpeel): Peels the empty even top side as Corner job , shifts port down onto the cut line with the same colour, and recurses Z on the bottom box.
- Double peel (
Horizontal cuts (hsplit, zoom,
hpeel) are skipped when the box is already wide
(
or
).
Colour-Bit Look-Ahead Without Backtracking
At the top of S zoom (and T zoom in Section
5), trying colour bit
and then
suffices to solve the entire two-path recursion with zero internal
backtracking:
- Bit fixes both ports: Selecting bit picks the first port cell on , determining ’s adjacent entry cell; ’s area parity determines its exit cell, fixing ’s entry, exit, and thus the second port cell on .
- Peels are colour-blind and colour-preserving: Cut
selection inside Z (and W) depends solely on box geometry and endpoint
positions. Each peel slices off an empty even-area side
holding port
and selects the new inner port
with
.
Its adjacent partner
inside
has opposite colour
,
so
stPathsucceeds on the even box for both colour bits and the shrunk child receives the exact same port colours. - Terminal compatibility: Both colour bits follow the
identical peel tree to the same terminal
sepor leaf. A terminalsepis compatible with at least one bit (both bits when the outer box was odd, one when even), and every leaf table entry is kernel-verified to succeed for at least one bit.
Implementation Details (Section 4 —
One.lean,OneLA.lean): - Base predicates:sLeaf(U, V);zLeaf(U, V);zWide(U, V). - S candidate order (sCandsOrd): - Near-square ():lsplit(midREvenOrdon ,midROrdon ) →sep(midROrd) →zoom(midROrd) →uturn→ fallbacksep(halfROrd). - Elongated ():sep(midROrd, long side first) →zoom→lsplit→uturn→ fallbacksep(halfROrd). - Z candidate order (zCandsOrd):hsplit→vsplit→zoom→vpeel→hpeel, all cuts inmidROrd.
5. Two Interior
Endpoints (tCan and Two-Path W Jobs)
Section Overview
Two-interior jobs cover near-square boxes
()
where both
and
lie strictly away from all corners. Top-level T jobs
(tCan) try a centered separating cut (T
sep) into two one-interior jobs; when
and
sit close together, they Zoom (tZoom) into
an even corner quadrant as a two-path W job
(wGo) so the outer 3/4 of the box remains pure Corner bulk.
Because both endpoints are free inside W, peeling can occur from any of
the four sides across two closed port layouts (O and
P) until a straight cut separates
from
.
Part A: Top-Level T Jobs
(tCan)
tCan translates the box to
and executes the first succeeding candidate from a 6-pass priority list
built from three moves:
- Separate (
tSep, panel a): Cuts vertically or horizontally between and , crossing once near a border edge into two one-interior jobs (onePath). Junction candidates try the far edge opposite the average transverse position of and first, forming a Hilbert U-arch. - Quadrant Zoom (
tZoom, panel b): Fences and inside an even corner quadrant (spawning a two-path W job), covers the outer L-shape with two Corner jobs , tries both colour bits , and glues forward or reversed according to W’s returned pairing flag (as in Ports and Free Pairing). - U-turn (
tUturn, panel c): Slices off an empty side strip as a Corner job and splits the remaining box perpendicular to the strip into two one-interior jobs .
Candidate ordering (axis stability and defect
localization): - Axis priority: Cut the longer
side first once aspect exceeds
(
or
);
within
,
cut the axis with larger endpoint separation
(
vs. ).
- Six passes (cuts ordered midOut): Pass 1
tries centered well-shaped tSep
().
Pass 2 tries centered well-shaped tZoom
(midROrd), isolating close endpoints into 1/4 of the box
while preserving 3/4 Hilbert bulk (panel b). Passes 3–6 try off-center
well-shaped tSep, off-center tZoom, thin
tSep, and tUturn.
For every box with
and aspect
,
tCan is proved complete (zero IPS fallback).
Part B: Two-Path W Jobs (Inside a T Zoom or Long-Box Ring)
A W job (wGo) covers an even-area
well-shaped box
with two disjoint paths connecting interior ends
to two corner ports
(near bottom-right) and
(near top-left), returning
with free pairing flag
.
Because both and are free, W peels from any of the four sides. Peeling the left edge moves onto the left vertical edge, forming a parallel-port configuration. Two canonical port layouts close cleanly under all four peel directions:
- Layout O (
lp = false): on right edge near bottom-right; on top edge near top-left. - Layout P (
lp = true): on right edge near bottom-right; on left edge near top-left. - Geometric invariant (
InvW): Even area,ShapeOK, and distinct and off all 4 port cells, no trapped corner adjacent to both and (¬ wTrap, panel a — a corner pinched by both ends is unreachable from both ports), and not one of the 10 infeasible Layout-O states (¬ wInf).
Reduction rules (using sep and peel
only):
- Small boxes
():
Lookup in
tabW, verified against the supplied ports viacoverB. - Separate (
sepx/sepy, panel b): Middle-third cut separating and into twoShapeOKhalves (each half even, or odd with its contained end matching that half’s corner colour). With zero crossings on the cut, each half already holds one endpoint and one port, so twoonePathcalls finish W and set the pairing flag . - Peel (
peelx/peely, panels c & d): Slices off an empty evenShapeOKside as a Corner job (stPath), shifts its port onto the cut line with the same colour (as in Colour-Bit Look-Ahead), and recurses into W on the ends’ half:
Completeness of
sep and peel on W
On every InvW box with
,
call a middle-third cut leaving two even ShapeOK halves a
good cut. If any good cut separates
and
,
sep is immediately valid. Otherwise, among the four extreme
good cuts (leftmost, rightmost, bottommost, topmost), a peel fails only
if an endpoint sits immediately next to that cut on a border edge
(blocking a new port cell or forming a trapped corner). Two endpoints
cannot simultaneously block extreme
-peels
and extreme
-peels
without violating InvW or allowing an extreme cut to
separate them. Because every peel is colour-blind and preserves port
colours bijectively, trying both colour bits at tZoom is
guaranteed to succeed. Boxes with
are finite and exhaustively kernel-verified in Lean
(TwoFinAll.lean).
Implementation Details (Section 5 —
Two.lean,TwoT.lean): - 4-way W peel transitions ( keeps viapickC; has colour ;cGosolves the peeled even box):
Peel direction Peeled corner box New port & junction Child frame & layout Gluing ( mapped back) peelx(c), ends right ()Left () , Shift ; Layout P ( true): else peelx(c), ends left ()Right () , Identity; keeps lp: else peely(r), ends top ()Bottom () , Frame ; flips !lp, portsFlag inverts: : else peely(r), ends bottom ()Top () , Identity; Layout O ( false): else
- W axis order (
wYFirst): Try Y before X iff , or ().- T split orientation (
spOrder):false(right full-height ) first if , elsetrue(top full-width ) first.- Infeasible
4 × 4O states (wInf):lp = false, , both .
6. Long Thick
Boxes (longPath,
,
aspect
)
Section Overview
longPath handles elongated boxes
()
with short side
.
The box is oriented with its long side vertical
()
and decomposed into pieces of aspect
joined end-to-end, keeping every slice at least
rows thick so dilation stays bounded by
.
Two Long-Box Helpers
- Long Corner Jobs (
lcGo): Extends Corner jobs to arbitrary aspect ratio. Once aspect , it delegates tostPath. Otherwise:- Ends on opposite short sides: halves horizontally near (made even if odd).
- Ends on the same short side: splits vertically into two parallel lanes at (made even if odd), joined at the far end (panel b of the both-interior diagram below).
- Rings (
ringOandringP): Wraps a near-square even two-path W box around endpoint(s) usinglcGolanes around the outside —ringOwhen sits at one end of the box (strip + top cap ), andringPwhen sits in the middle (bottom cap + full-height strip + top cap ; panels d & e below).
Long
One-Interior (lsGo) and Both-Interior (ltCan)
Control Paths
When either endpoint lies near a corner, longPath
invokes lsGo; otherwise it invokes ltCan.
Long one-interior (lsGo,
near bottom-left): Delegates to onePath if aspect
,
or lcGo if
is also near a corner. Otherwise tries four patterns in order:
- Top cap (Step 2): Places a near-square
onePathcap ( tall) containing above alcGobase. - Bottom
ringO(Step 3): Wraps both and inside a bottomringObox . - Mid
ringOoverlcGo(Step 4): Mirrors horizontally so is on the left, placeslcGobelow , and wraps inside aringObox above it. - Single-level column split (Step 5): Runs
lcGoup the left column andlsGo1(identical tolsGowithout Step 5, so column width halves at most once) down the right column.
Long both-interior (ltCan, both ends
interior): Tries three patterns in order:
- Horizontal split (
ltSplit, panel a): Cuts horizontally between and near (both halves rows tall) and solves both halves vialsGo. - Horizontal band (
bandCan, panel c): Encloses horizontally separated ends at similar heights in a band split into 2 columns (at the bottom) or 3 roughly square columns (in the middle: leftonePath→ toplsGo→ middle Corner → bottomlsGo→ rightonePath). - Ring (
ringCan, panels d & e): Encloses close endpoints inside a two-path W box viaringO(at an end) orringP(in the middle), trying vertical flips and horizontal mirrors.
Implementation Details (Section 6 —
Long.lean): - Minimum slice thickness:abL(U). - Ring strip widths (wsL(U)): . - Parity helper:needC(L, a)ifevenB(L), else . - Band / ring heights:bandCantries () with column widths ;ringPkeeps bottom cap .
7. Long
Narrow Boxes (narrowPath,
,
aspect
)
Section Overview
narrowPath handles elongated boxes
()
with short side
,
where multi-lane rings would create strips narrower than 4 cells.
Orienting the long side vertical
(),
it solves a core block tightly bracketing
and
and splices recursively tiled Hilbert-like excursions onto the empty
ends above and below the core.
Corner-Edge Splicing, Tiled Excursions, and Full Assembly
- Corner-edge splicing (
spliceAt, panel a): A corner cell of any rectangle has exactly two neighbours inside the rectangle: (along the cut edge) and (along the side wall). Every Hamiltonian path whose endpoints differ from traverses both incident edges of , guaranteeing that appears consecutively in the path. Opening splices in any Hamiltonian excursion on an adjacent box whose endpoints lie adjacent to and . - Tiled crinkly excursions (
excTile, panel b): To fill an empty even-height strip from to with short runs, a single near-squareonePathtile solves . Larger heights solve a roughly square bottom tile of even height viaonePath, recursively buildexcTile(U, H - h1), mirror it horizontally, and splice it into the bottom tile’s top-right corner edge. Alternating left/right mirrors at every level keeps every tile crinkly and Hilbert-like. - Core + excursion assembly (
nCore+nCan, panel c):- Bracket and in a core leaving at least 4 rows below and 5 rows above (rounded so any remaining top/bottom strip has even height ).
- Solve the core with one
stgPathcall when , or with three stacked blocks (stgPatharound ,lcGomiddle bridge,stgPatharound ) when . - Splice
excTileonto the core’s top-right corner (when ) and bottom-left corner (when ).
Implementation Details (Section 7 —
Narrow.lean): - Minimum even excursion height:minExcH(U)rounded up to even ( for ). - Single-tile cap:singleMax(U). - Tile height: ; use rounded down to even if , else . - Core rows: if else ; if else . Far-end splits: , .
8. Base-Case Leaf Tables & IPS Fallback
Section Overview
Recursive calls below the cut thresholds terminate in five finite
move-word tables (exported to ref/data/tables.json and
ref/c/stgfull_tables.c), complemented by the standard IPS
solver for thin strips
()
and rare small-box fallbacks
().
| Table / Solver | Used by | Shapes covered | Required entry invariants |
|---|---|---|---|
tab1 |
Corner (stPath) |
(1,576 entries) | Valid 1-path Inv1 cover; max run
cells; exact 2D Hilbert on
&
;
Euclidean PreB 15, SufB 15,
SegB 32. |
tab2 |
Corner (case2b) |
Even , (160 entries) | Valid 2-path strip cover; max run
cells; Euclidean PreB 15, SufB 15,
SegB 32. |
tabG |
One-interior (sLeaf) |
, or | Valid 1-path cover; max run cells (Hilbert-affinity optimized). |
tabZo / tabZs |
Two-path Z & uturn |
Even, or () | Valid 2-path cover for at least one colour bit ; max run cells. |
tabW |
Two-path W (wSmall) |
Even, (~20,763 entries) | Valid 2-path cover for some admissible port colouring on all
InvW leaves & small exceptions; max run
cells. |
ipsBox |
min ≤ 3, rare min < 20 fallback |
All acceptable grids | Standard constructive Itai–Papadimitriou–Szwarcfiter (1982) solver (strip peeling + prime base shapes up to ). |
Alternative to precomputed tables: Implementations that target the same asymptotic and aesthetic properties without bit-for-bit Lean vector equality can replace
tabG,tabZo/tabZs, andtabWwith a memoized bounded backtracking solver minimizing straight-run length (– cells) and returning exact Hilbert on and .
9. Proved Guarantees & Implementation Checklist
Metric Definitions
- Max straight run: longest sequence of consecutive cells moving along a single row or column (in cells; identical moves = cells).
- Turn density & average run: fraction of consecutive move pairs that make a 90° turn (2D Hilbert curve: 75% turns, average run 2.33 cells).
- Squared Euclidean dilation (): worst-case ratio of squared Euclidean endpoint distance to segment cell count over all contiguous sub-segments of the path: where are the first and last cells of . For the classic 2D Hilbert curve, . On elongated rectangles of aspect ratio , every Hamiltonian path satisfies because spanning the long side covers at most cells ().
Formally Proved Bounds vs. Measured Performance
All theorems below are formally proved in Lean 4
(lean/StGilbert/, standard axioms
[propext, Classical.choice, Quot.sound] only, zero
sorry, zero native_decide):
| Property | Scope | Proved Bound | Measured (v5_stable C, sampled) |
|---|---|---|---|
| Existence & Exactness | Every , any distinct | Path exists
IpsAcc; stgFull builds it |
0 diffs across 33,504 paths + 1,852 units |
| Exact 2D Hilbert | (), | Identical to classic 2D Hilbert curve | Exact for all tested |
| Max Straight Run | Corner (stPath) |
cells | – cells |
One-interior (onePath) |
cells | – cells | |
Near-square rules (stgRules) |
cells | – cells | |
Long boxes
(,
stgAll) |
cells | – cells | |
All boxes with
(stgFull) |
cells | – cells | |
| Turn Density / Avg Run | Corner (stPath) |
turns (avg run ) | – (avg ) |
One-interior (onePath) |
turns (avg run ) | – (avg ) | |
stgAll / stgRules /
longPath |
turns (avg run ) | – (avg ) | |
Narrow tiles (excTile) |
turns (avg run ) | – (avg ) | |
| Euclidean Dilation | Corner (stPath) |
( Hilbert’s ) | – |
One-interior (onePath) |
( Hilbert) | – | |
| Near-square (, aspect ) | ( Hilbert) | – (squares), up to | |
| All boxes & aspects () | – () |
Practical Implementation Checklist
- Integer arithmetic: All
/are floor integer division; natural-number subtractions inmidOut/clampNsaturate at (clamp explicitly in signed-integer languages). - Memory management: In
tCanandlongPath, free failed candidate paths immediately before trying the next candidate so peak memory stays . - Runtime cover validation (
coverB): Verify bounds, endpoints, unit steps, uniqueness, and exact cell count on table lookups — this also filters port colours intabW. - Rebuilding this document: Run
./docs/build.shfrom the repository root to regenerate all 19 SVG figures viaref/c/stgfulland compiledocs/ALGORITHM.mdintodocs/ALGORITHM.htmlviapandoc --mathml(native offline HTML5 MathML; zero external dependencies).