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 w×hw \times h integer grid from start cell ss to end cell tt (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):

  1. Spatial locality (bounded dilation): Cells that are close along the 1D curve remain close in 2D Euclidean distance; every contiguous segment of length LL stays within a diameter of O(L)O(\sqrt{L}) on bounded-aspect rectangles.
  2. 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.
  3. Exact 2D Hilbert identity: On every power-of-two square 2k×2k2^k \times 2^k (k≥2k \ge 2) with endpoints (0,0)(0, 0) and (2k−1,0)(2^k - 1, 0), the output is identical to the classic 2D Hilbert curve.
  4. Localized endpoint disruption and stability: Routing around interior endpoints stays confined to a small sub-region around ss and tt, leaving the bulk of the grid Hilbert-like and keeping most edges unchanged under small shifts of size or endpoints.
Comparison on 16x16 between a column-by-column Hamiltonian snake (grid-length runs, poor 2D locality) and st-Gilbert v5_stable (Hilbert-like space-filling curve with maxRun = 4, 80% turns, and D2 = 4.32).
Stability and defect localization: moving endpoint t inward from an exact 16x16 Hilbert curve confines changes to the sub-quadrant containing t, preserving 90%–99.6% of bulk edges.

Existence Criterion

Colour the grid like a checkerboard: cell (x,y)(x, y) is dark when x+yx + y is even and light when x+yx + y is odd. Because every unit step alternates colours, a Hamiltonian path from ss to tt requires colour compatibility:

For all grids with w≥4w \ge 4 and h≥4h \ge 4, colour compatibility is both necessary and sufficient. For grids with min(w,h)≤3\min(w, h) \le 3, Itai, Papadimitriou, and Szwarcfiter (1982; IPS) showed that a finite family of thin-strip separation obstructions must also be excluded.

Checkerboard colour compatibility on odd and even grids, alongside a thin-strip IPS obstruction on 2x6.

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:

The four building-block job types: recursive cuts reduce every sub-problem down toward Corner jobs.
  1. 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.
  2. One-interior job (green) — one endpoint lies within distance 1 of a corner; the other lies anywhere inside.
  3. Two-interior job (indigo) — both endpoints lie anywhere inside.
  4. 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 ss and tt sit close together in one corner of a box, isolating them inside a corner quadrant QQ allows the outer L-shaped 3/4 of the box to be filled by two Corner jobs (R1R_1 and R2R_2). The complete path starts at ss inside QQ, exits QQ through a border cell (port A or port B), traverses the outer bridge R1+R2R_1 + R_2, re-enters QQ through the other port, and finishes at tt.

Because the outer bridge R1→R2R_1 \to R_2 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:

Ports are the two doorway cells linking a zoomed quadrant Q to the outer corner bridge R1 + R2. The returned pairing flag selects whether the outer bridge is glued forward (flag = false) or reversed (flag = true).

Allowing free pairing eliminates the crossing obstructions of general k=2k = 2 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:

The three universal moves: Separate cuts between s and t; Zoom fences close ends into a 2-path quadrant; Peel slices an empty side off a 2-path box to shrink it toward Separate.
  1. Separate (sep): Cut straight across the box with ss and tt 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.
  2. 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.
  3. 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 until sep separates 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 u=min(w,h)u = \min(w, h) and aspect ratio α=max(w,h)/min(w,h)\alpha = \max(w, h) / \min(w, h):

Top-level dispatch regimes of stgFull in (short side, aspect ratio) space, with proved run and dilation bounds per regime.
  1. Thin strips (u≤3u \le 3): 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 u≥4u \ge 4.
  2. Near-square (u≥4u \ge 4, α≤9/4\alpha \le 9/4): Solved by the core recursive rules (Sections 3–5). For u≥20u \ge 20, these rules are proved complete with zero fallback; for 4≤u≤194 \le u \le 19, any state where the two-interior rules return empty falls back to ipsBox.
  3. Long and thick (u≥20u \ge 20, α>9/4\alpha > 9/4): Solved by longPath (Section 6), which decomposes the elongated box into near-square pieces of aspect ≤3\le 3 handled by the core rules.
  4. Long and narrow (4≤u≤194 \le u \le 19, α>9/4\alpha > 9/4): Solved by narrowPath (Section 7), which solves a core block around ss and tt 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

The three shared conventions: (1) well-shaped sub-boxes (sides >= 4, aspect <= 3); (2) 2-cell corner junctions matching checkerboard parity; (3) centered middle-out cuts in [L/3, 2L/3].
  1. Well-shaped sub-boxes (ShapeOK): Every recursive piece in Sections 3–5 satisfies min(w,h)≥4\min(w, h) \ge 4 and max(w,h)≤3min(w,h)\max(w, h) \le 3\min(w, h). Keeping all pieces well-shaped bounds both straight runs and Euclidean dilation.
  2. 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 ≤1\le 1 from the corner). Because these two adjacent cells have opposite checkerboard colours, one always matches the colour required by the sub-box.
  3. Centered middle-out cuts (midOut) and canonical frames (ffr/fto): Cut candidates are ordered outward from the midpoint (⌊L/2⌋,⌊L/2⌋+1,⌊L/2⌋−1,…\lfloor L/2 \rfloor, \lfloor L/2 \rfloor+1, \lfloor L/2 \rfloor-1, \dots) inside the middle third [L/3,2L/3][L/3, 2L/3]. Rules are defined once in a canonical origin box [0,U)×[0,V)[0, U) \times [0, V) by transforming the box in (ffr) and mapping the resulting path back out (fto).

Parity of Cut Sub-Boxes and Endpoint Classification


3. Corner Jobs (stPath)

Section Overview

Corner jobs cover any well-shaped box (ShapeOK) with endpoints a,ba, b within distance 1 of two distinct corners. After normalizing orientation (h≤wh \le w, aa on the left edge, and aa at bottom-left if both ends are on the left), boxes with w≤11w \le 11 return a stored Hilbert-like leaf path from tab1. Larger boxes (w≥12w \ge 12) 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

Layer 1 (stPath) corner job decomposition rules on real v5_stable curves: Rule 3 (bottom and transposed left), Rule 1 (vertical bisection), and Rule 2b (elongated strip U-turn).
  1. Near-square U-turn (Rule 3, panels a & b): Applies when both ends lie on the same edge (bottom, top, or left) and 2w≤3h2w \le 3h. Splits into three Corner boxes forming a Hilbert U-turn: two lower boxes B1,B3B_1, B_3 flanking a full-span opposite half B2B_2. Ends on the left edge apply this rule in the transposed frame; ends on the top edge mirror vertically first.
  2. Vertical bisection (Rule 1, panel c): Applies when the ends lie on opposite sides (left and right) and Rule 3 is inactive (either 2w>3h2w > 3h or the ends sit at diagonally opposite corners). Splits vertically near w/2w/2 and crosses once near the bottom of the cut.
  3. Elongated strip U-turn (Rule 2b, panel d): Applies when both ends lie on the same short side (left edge) and 2w>3h2w > 3h. Slices off an even-width left strip carrying two paths (aa exiting at bottom-right, bb entering at top-right), joined across two junctions to one Corner job on the right remainder. Strips with both sides ≤11\le 11 use stored two-path table tab2; larger strips split horizontally at ⌊h/2⌋\lfloor h/2 \rfloor into two Corner jobs.

Exact 2D Hilbert Recursion

On every 2k×2k2^k \times 2^k square (k≥4k \ge 4) with endpoints (0,0)(0, 0) and (2k−1,0)(2^k - 1, 0), Rule 3 cuts at r=2k−1r = 2^{k-1} and w/2=2k−1w/2 = 2^{k-1}, producing two lower 2k−1×2k−12^{k-1} \times 2^{k-1} quadrants Q0,Q3Q_0, Q_3 and one top rectangle B2B_2 of size 2k×2k−12^k \times 2^{k-1}. Because B2B_2 has aspect ratio 2>3/22 > 3/2 with endpoints at its bottom corners, the next recursive call immediately applies Rule 1 to bisect B2B_2 vertically into the two upper quadrants Q1,Q2Q_1, Q_2. Together with exact Hilbert 4×44 \times 4 and 8×88 \times 8 leaves in tab1, this produces the exact 2D Hilbert curve for all k≥2k \ge 2.

Three-step diagram showing how 3-box Rule 3 followed by 2-box Rule 1 on the top half reproduces the exact 4-quadrant 2D Hilbert curve.

Implementation Details (Section 3 — Corner.lean): - Invariant Inv1(B, a, b): ShapeOK(B), Compat(B, a, b), a,ba, b within Manhattan distance ≤1\le 1 of two distinct corners (NearC). - Normalization: Transpose if w<hw < h; lookup tab1 if w≤11w \le 11; mirror left-right (refl) if both ends have x>x0+1x > x_0 + 1; swap (a,b)(a, b) and reverse output if ¬First(B, a, b). - Cut formulas: - Rule 1: cut1(w, h) =⌊w/2⌋= \lfloor w/2 \rfloor, minus 11 if hh odd and ⌊w/2⌋\lfloor w/2 \rfloor odd. - Rule 3: r3h(h) =largest even≤⌊h/2⌋= \text{largest even} \le \lfloor h/2 \rfloor; bottom widths ⌊w/2⌋\lfloor w/2 \rfloor and w−⌊w/2⌋w - \lfloor w/2 \rfloor. - Rule 2b: cs2b(w, h) =largest even≤min(⌊w/2⌋,3⌊h/2⌋)= \text{largest even} \le \min(\lfloor w/2 \rfloor, 3\lfloor h/2 \rfloor). (A legacy Ok2a/case2a branch remains in code for proof continuity, though 2w>3h2w > 3h implies w>3⌊h/2⌋w > 3\lfloor h/2 \rfloor, so transposed case3 handles every Ok2a-eligible box first.) - Junction parity: Each crossing cell is offset by flipK(q, p) ∈ {0, 1} along the cut so the first child’s endpoint has colour opposite to aa (or bb).


4. One Interior Endpoint (onePath: S and Z Jobs)

Section Overview

One-interior jobs cover a well-shaped box where endpoint π\pi lies within distance 1 of a corner and endpoint xx lies anywhere inside. When xx also lies within distance 1 of another corner, the box delegates immediately to a Corner job (Section 3). Otherwise, the box is framed with π\pi near (0,0)(0, 0) in [0,U)×[0,V)[0, U) \times [0, V) 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 xx lies near π\pi’s corner; Z jobs repeatedly Peel empty even sides as Corner jobs until a straight cut separates π\pi from xx.

Part A: One-Path S Jobs (π→x\pi \to x)

Small boxes (max≤7\max \le 7, or max≤9\max \le 9 and min≤7\min \le 7) 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:

Layer 2 (onePath) S-job control paths: lsplit (near-square priority), sep (elongated), zoom into Z, and thin-box uturn.
  1. L-split (lsplit, panel a — first on near-squares 2max≤3min2\max \le 3\min): Partitions into three well-shaped pieces: two Corner jobs (C1C_1 bottom-left, C2C_2 full-height right) plus a smaller one-interior job in the top-left containing xx, preserving a Hilbert U-turn across 3/4 of the box.
  2. Separate (sep, panel b — first on elongated boxes 2max>3min2\max > 3\min): Cuts vertically between π\pi and xx into a Corner job (holding π\pi) and a smaller one-interior job (holding xx), crossing once near either end of the cut.
  3. Zoom into Z (zoom, panel c): When xx lies in the bottom-left quadrant [0,c)×[0,r)[0, c) \times [0, r) (off its 4 inner port cells), selects an even-area quadrant QQ for a two-path Z job and covers the outer right and top-left boxes with Corner jobs PR,PTP_R, P_T. When U⋅VU \cdot V is even, both PRP_R and PTP_T are even; when U⋅VU \cdot V is odd, one outer Corner box absorbs the oddness.
  4. Thin-box U-turn (uturn, panel d): Slices off an even leaf strip holding π\pi and xx (solved by stored 2-path table tabZs) 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 QQ (transposed if needed so U≥VU \ge V) to a Z job with π\pi near (0,0)(0, 0), xx inside, and two border ports: E1E_1 (right edge near bottom-right) and E2E_2 (top edge near top-left). As shown in Ports and Free Pairing, Z returns two disjoint paths (P1,P2)(P_1, P_2) and a pairing flag: - flag = false (H pairing): π→E1\pi \to E_1 and E2→xE_2 \to x (outer bridge PR+PTP_R + P_T glued forward). - flag = true (V pairing): π→E2\pi \to E_2 and E1→xE_1 \to x (outer bridge glued in reverse).

Small boxes (zLeaf) look up tabZo. Larger boxes take the first valid middle-third cut from five rules:

Layer 2 Z two-path decomposition rules: hsplit, vsplit, zoom, vpeel, and hpeel on canonical U x V boxes.

Horizontal cuts (hsplit, zoom, hpeel) are skipped when the box is already wide (3V<2U3V < 2U or V<8V < 8).

Colour-Bit Look-Ahead Without Backtracking

At the top of S zoom (and T zoom in Section 5), trying colour bit a=0a = 0 and then a=1a = 1 suffices to solve the entire two-path recursion with zero internal backtracking:

Colour-bit propagation pipeline: bit a fixes ports (cA, cB) at the top zoom; every peel is colour-blind and preserves (cA, cB) identically down to the terminal sep or leaf, where at least one of a in {0, 1} matches.
  1. Bit aa fixes both ports: Selecting bit a∈{0,1}a \in \{0, 1\} picks the first port cell on QQ, determining R1R_1’s adjacent entry cell; R1R_1’s area parity determines its exit cell, fixing R2R_2’s entry, exit, and thus the second port cell on QQ.
  2. 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 RR holding port pp and selects the new inner port npn_p with col(np)=col(p)\operatorname{col}(n_p) = \operatorname{col}(p). Its adjacent partner jcj_c inside RR has opposite colour 1−col(p)1 - \operatorname{col}(p), so stPath succeeds on the even box RR for both colour bits and the shrunk child receives the exact same port colours.
  3. Terminal compatibility: Both colour bits follow the identical peel tree to the same terminal sep or leaf. A terminal sep is compatible with at least one bit a∈{0,1}a \in \{0, 1\} (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) ≡max≤7∨(max≤9∧min≤7)\equiv \max \le 7 \lor (\max \le 9 \land \min \le 7); zLeaf(U, V) ≡max≤7∨(min≤7∧max≤8)\equiv \max \le 7 \lor (\min \le 7 \land \max \le 8); zWide(U, V) ≡3V<2U∨V<8\equiv 3V < 2U \lor V < 8. - S candidate order (sCandsOrd): - Near-square (2max≤3min2\max \le 3\min): lsplit (midREvenOrd on cc, midROrd on rr) → sep (midROrd) → zoom (midROrd) → uturn → fallback sep (halfROrd). - Elongated (2max>3min2\max > 3\min): sep (midROrd, long side first) → zoom → lsplit → uturn → fallback sep (halfROrd). - Z candidate order (zCandsOrd): hsplit → vsplit → zoom → vpeel → hpeel, all cuts in midROrd.


5. Two Interior Endpoints (tCan and Two-Path W Jobs)

Section Overview

Two-interior jobs cover near-square boxes (α≤9/4\alpha \le 9/4) where both ss and tt lie strictly away from all corners. Top-level T jobs (tCan) try a centered separating cut (T sep) into two one-interior jobs; when ss and tt 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 ss from tt.

Part A: Top-Level T Jobs (tCan)

tCan translates the box to [0,U)×[0,V)[0, U) \times [0, V) and executes the first succeeding candidate from a 6-pass priority list built from three moves:

Layer 3 (tCan) T-job control paths: centered tSep, centered tZoom isolating close endpoints into a single W quadrant, and tUturn.
  1. Separate (tSep, panel a): Cuts vertically or horizontally between ss and tt, crossing once near a border edge into two one-interior jobs (onePath). Junction candidates try the far edge opposite the average transverse position of ss and tt first, forming a Hilbert U-arch.
  2. Quadrant Zoom (tZoom, panel b): Fences ss and tt inside an even corner quadrant [0,c)×[0,r)[0, c) \times [0, r) (spawning a two-path W job), covers the outer L-shape with two Corner jobs R1,R2R_1, R_2, tries both colour bits a∈{false,true}a \in \{\text{false}, \text{true}\}, and glues R1→R2R_1 \to R_2 forward or reversed according to W’s returned pairing flag (as in Ports and Free Pairing).
  3. U-turn (tUturn, panel c): Slices off an empty side strip as a Corner job RsR_s and splits the remaining box perpendicular to the strip into two one-interior jobs B0,B1B_0, B_1.

Candidate ordering (axis stability and defect localization): - Axis priority: Cut the longer side first once aspect exceeds 4/34/3 (3U>4V3U > 4V or 3V>4U3V > 4U); within 4/34/3, cut the axis with larger endpoint separation (|sy−ty||s_y - t_y| vs. |sx−tx||s_x - t_x|). - Six passes (cuts ordered midOut): Pass 1 tries centered well-shaped tSep (c∈[3L/8,5L/8]c \in [3L/8, 5L/8]). 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 U,V≥20U, V \ge 20 and aspect ≤9/4\le 9/4, 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 U×VU \times V with two disjoint paths connecting interior ends s,ts, t to two corner ports pap_a (near bottom-right) and pbp_b (near top-left), returning (P1,P2,f)(P_1, P_2, f) with free pairing flag ff.

Because both ss and tt are free, W peels from any of the four sides. Peeling the left edge moves pbp_b onto the left vertical edge, forming a parallel-port configuration. Two canonical port layouts close cleanly under all four peel directions:

Canonical W job layouts O and P, trapped-corner obstruction (wTrap), and the sep and peel reduction steps.

Reduction rules (using sep and peel only):

  1. Small boxes (min≤9,max≤27\min \le 9, \max \le 27): Lookup in tabW, verified against the supplied ports via coverB.
  2. Separate (sepx / sepy, panel b): Middle-third cut separating ss and tt into two ShapeOK halves (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 two onePath calls finish W and set the pairing flag ff.
  3. Peel (peelx / peely, panels c & d): Slices off an empty even ShapeOK side 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:
All four W-peel directions showing exact new port np (colour preserved), junction jc (opposite colour), corner path PR, and resulting O <-> P layout transition.

Completeness of sep and peel on W

On every InvW box with U,V≥10U, V \ge 10, call a middle-third cut leaving two even ShapeOK halves a good cut. If any good cut separates ss and tt, 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 xx-peels and extreme yy-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 min≤9\min \le 9 are finite and exhaustively kernel-verified in Lean (TwoFinAll.lean).

Implementation Details (Section 5 — Two.lean, TwoT.lean): - 4-way W peel transitions (npn_p keeps col(pout)\operatorname{col}(p_{\text{out}}) via pickC; jcj_c has colour 1−col(pout)1 - \operatorname{col}(p_{\text{out}}); cGo solves the peeled even box):

Peel direction Peeled corner box RR New port npn_p & junction jcj_c Child frame & layout Gluing (z′z' mapped back)
peelx(c), ends right (c≤sx,txc \le s_x, t_x) Left [0,c)×[0,V)[0, c) \times [0, V) (pb→jcp_b \to j_c) np∈{(c,V−1),(c,V−2)}n_p \in \{(c, V-1), (c, V-2)\}, jc=(c−1,np,y)j_c = (c-1, n_{p,y}) Shift x↦x−cx \mapsto x - c; Layout P (true) f′f': (P1+rev(PR),P2,true)(P_1 + \mathrm{rev}(P_R), P_2, \text{true}) else (P1,PR+P2,false)(P_1, P_R + P_2, \text{false})
peelx(c), ends left (sx,tx<cs_x, t_x < c) Right [c,U)×[0,V)[c, U) \times [0, V) (pa→jcp_a \to j_c) np∈{(c−1,0),(c−1,1)}n_p \in \{(c-1, 0), (c-1, 1)\}, jc=(c,np,y)j_c = (c, n_{p,y}) Identity; keeps lp ff: (P1,PR+P2,true)(P_1, P_R + P_2, \text{true}) else (P1+rev(PR),P2,false)(P_1 + \mathrm{rev}(P_R), P_2, \text{false})
peely(r), ends top (r≤sy,tyr \le s_y, t_y) Bottom [0,U)×[0,r)[0, U) \times [0, r) (pa→jcp_a \to j_c) np∈{(U−1,r),(U−2,r)}n_p \in \{(U-1, r), (U-2, r)\}, jc=(np,x,r−1)j_c = (n_{p,x}, r-1) Frame k=(lp,lp),sw=¬lpk=(\mathrm{lp},\mathrm{lp}), \mathrm{sw}=\neg\mathrm{lp}; flips !lp, ports (ffr(pb),ffr(np))(\mathrm{ffr}(p_b), \mathrm{ffr}(n_p)) Flag inverts: f′f': (P1+rev(PR),P2,false)(P_1 + \mathrm{rev}(P_R), P_2, \text{false}) else (P1,PR+P2,true)(P_1, P_R + P_2, \text{true})
peely(r), ends bottom (sy,ty<rs_y, t_y < r) Top [0,U)×[r,V)[0, U) \times [r, V) (pb→jcp_b \to j_c) np∈{(0,r−1),(1,r−1)}n_p \in \{(0, r-1), (1, r-1)\}, jc=(np,x,r)j_c = (n_{p,x}, r) Identity; Layout O (false) ff: (P1+rev(PR),P2,true)(P_1 + \mathrm{rev}(P_R), P_2, \text{true}) else (P1,PR+P2,false)(P_1, P_R + P_2, \text{false})
  • W axis order (wYFirst): Try Y before X iff 3V>4U3V > 4U, or (3U≤4V∧|sy−ty|>|sx−tx|3U \le 4V \land |s_y - t_y| > |s_x - t_x|).
  • T split orientation (spOrder): false (right full-height R1R_1) first if V≤UV \le U, else true (top full-width R1R_1) first.
  • Infeasible 4 × 4 O states (wInf): lp = false, U=V=4U = V = 4, both s,t∈{(1,0),(0,1),(2,1),(1,2)}s, t \in \{(1,0), (0,1), (2,1), (1,2)\}.

6. Long Thick Boxes (longPath, min≥20\min \ge 20, aspect >9/4> 9/4)

Section Overview

longPath handles elongated boxes (α>9/4\alpha > 9/4) with short side u≥20u \ge 20. The box is oriented with its long side vertical (U≤VU \le V) and decomposed into pieces of aspect ≤3\le 3 joined end-to-end, keeping every slice at least abL(U)=max(8,⌈U/3⌉)\mathrm{abL}(U) = \max(8, \lceil U/3 \rceil) rows thick so dilation stays bounded by O(α)O(\alpha).

Two Long-Box Helpers

  1. Long Corner Jobs (lcGo): Extends Corner jobs to arbitrary aspect ratio. Once aspect ≤3\le 3, it delegates to stPath. Otherwise:
    • Ends on opposite short sides: halves horizontally near V/2V/2 (made even if UU odd).
    • Ends on the same short side: splits vertically into two parallel lanes at U/2U/2 (made even if VV odd), joined at the far end (panel b of the both-interior diagram below).
  2. Rings (ringO and ringP): Wraps a near-square even two-path W box MM around endpoint(s) using lcGo lanes around the outside — ringO when MM sits at one end of the box (strip SS + top cap AA), and ringP when MM sits in the middle (bottom cap DD + full-height strip SS + top cap AA; 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, pp near bottom-left): Delegates to onePath if aspect ≤3\le 3, or lcGo if xx is also near a corner. Otherwise tries four patterns in order:

Layer 4 (lsGo) long one-interior control paths: top cap, bottom ringO, mid ringO over lcGo, and single-level column split.

Long both-interior (ltCan, both ends interior): Tries three patterns in order:

Layer 4 (longPath) control paths: real ltSplit and same-edge lcGo curves, plus schematics for 3-column bandCan, ringO, and ringP.
  1. Horizontal split (ltSplit, panel a): Cuts horizontally between ss and tt near V/2V/2 (both halves ≥abL(U)\ge \mathrm{abL}(U) rows tall) and solves both halves via lsGo.
  2. 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: left onePath → top lsGo → middle Corner → bottom lsGo → right onePath).
  3. Ring (ringCan, panels d & e): Encloses close endpoints inside a two-path W box MM via ringO (at an end) or ringP (in the middle), trying vertical flips and horizontal mirrors.

Implementation Details (Section 6 — Long.lean): - Minimum slice thickness: abL(U) =max(8,⌈U/3⌉)= \max(8, \lceil U/3 \rceil). - Ring strip widths (wsL(U)): [⌊U/2⌋,⌊U/2⌋+1,max(4,⌊U/4⌋),max(4,⌊U/4⌋)+1][\lfloor U/2 \rfloor, \lfloor U/2 \rfloor + 1, \max(4, \lfloor U/4 \rfloor), \max(4, \lfloor U/4 \rfloor) + 1]. - Parity helper: needC(L, a) =1−col(a)= 1 - \operatorname{col}(a) if evenB(L), else (L.x0+L.y0)mod2(L.x_0 + L.y_0) \bmod 2. - Band / ring heights: bandCan tries H0=max(4,max(Δy+1,⌊U/3⌋))+dhH_0 = \max(4, \max(\Delta y + 1, \lfloor U/3 \rfloor)) + dh (dh∈{0,1}dh \in \{0, 1\}) with column widths ≥max(4,⌈H/3⌉)\ge \max(4, \lceil H/3 \rceil); ringP keeps bottom cap a≥max(8,⌊U/6⌋)a \ge \max(8, \lfloor U/6 \rfloor).


7. Long Narrow Boxes (narrowPath, 4≤min≤194 \le \min \le 19, aspect >9/4> 9/4)

Section Overview

narrowPath handles elongated boxes (α>9/4\alpha > 9/4) with short side 4≤U≤194 \le U \le 19, where multi-lane rings would create strips narrower than 4 cells. Orienting the long side vertical (sy≤tys_y \le t_y), it solves a core block tightly bracketing ss and tt and splices recursively tiled Hilbert-like excursions onto the empty ends above and below the core.

Corner-Edge Splicing, Tiled Excursions, and Full Assembly

Layer 5 (narrowPath): topological proof of corner-edge splicing (spliceAt), real excTile alternating-mirror tiling on 30x6, and full 5-part narrowPath assembly on 48x8.
  1. Corner-edge splicing (spliceAt, panel a): A corner cell cc of any rectangle has exactly two neighbours inside the rectangle: c′c' (along the cut edge) and dd (along the side wall). Every Hamiltonian path whose endpoints differ from cc traverses both incident edges of cc, guaranteeing that (c,c′)(c, c') appears consecutively in the path. Opening (c,c′)(c, c') splices in any Hamiltonian excursion QQ on an adjacent box whose endpoints lie adjacent to cc and c′c'.
  2. Tiled crinkly excursions (excTile, panel b): To fill an empty even-height strip U×HU \times H from (0,0)(0, 0) to (1,0)(1, 0) with short runs, a single near-square onePath tile solves H≤singleMax(U)H \le \mathrm{singleMax}(U). Larger heights solve a roughly square bottom tile of even height h1≈Uh_1 \approx U via onePath, recursively build excTile(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.
  3. Core + excursion assembly (nCore + nCan, panel c):
    • Bracket ss and tt in a core [y0,y1)[y_0, y_1) leaving at least 4 rows below ss and 5 rows above tt (rounded so any remaining top/bottom strip has even height ≥minExcH(U)\ge \mathrm{minExcH}(U)).
    • Solve the core with one stgPath call when ty−sy≤12t_y - s_y \le 12, or with three stacked blocks (stgPath around ss, lcGo middle bridge, stgPath around tt) when ty−sy>12t_y - s_y > 12.
    • Splice excTile onto the core’s top-right corner (when y1<Vy_1 < V) and bottom-left corner (when y0>0y_0 > 0).

Implementation Details (Section 7 — Narrow.lean): - Minimum even excursion height: minExcH(U) =max(4,⌈U/3⌉)= \max(4, \lceil U/3 \rceil) rounded up to even (≤8\le 8 for U≤19U \le 19). - Single-tile cap: singleMax(U) =min(3U,max(2⋅minExcH(U),U+⌊U/2⌋))= \min(3U, \max(2 \cdot \mathrm{minExcH}(U), U + \lfloor U/2 \rfloor)). - Tile height: h0=U+(Umod2)h_0 = U + (U \bmod 2); use ⌊H/2⌋\lfloor H/2 \rfloor rounded down to even if H−h0<minExcH(U)H - h_0 < \mathrm{minExcH}(U), else h0h_0. - Core rows: y0=even(sy−4)y_0 = \text{even}(s_y - 4) if sy≥minExcH(U)+4s_y \ge \mathrm{minExcH}(U) + 4 else 00; y1=ty+5+((V−ty−5)mod2)y_1 = t_y + 5 + ((V - t_y - 5) \bmod 2) if ty+5+minExcH(U)≤Vt_y + 5 + \mathrm{minExcH}(U) \le V else VV. Far-end splits: a=sy+4+((sy+4−y0)mod2)a = s_y + 4 + ((s_y + 4 - y_0) \bmod 2), b=ty−3−((ty−3−a)mod2)b = t_y - 3 - ((t_y - 3 - a) \bmod 2).


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 (min≤3\min \le 3) and rare small-box fallbacks (min<20\min < 20).

Table / Solver Used by Shapes covered Required entry invariants
tab1 Corner (stPath) 4≤h≤w≤114 \le h \le w \le 11 (1,576 entries) Valid 1-path Inv1 cover; max run ≤6\le 6 cells; exact 2D Hilbert on 4×44 \times 4 & 8×88 \times 8; Euclidean PreB 15, SufB 15, SegB 32.
tab2 Corner (case2b) Even cs∈{6,8,10}c_s \in \{6, 8, 10\}, 4≤h≤114 \le h \le 11 (160 entries) Valid 2-path strip cover; max run ≤6\le 6 cells; Euclidean PreB 15, SufB 15, SegB 32.
tabG One-interior (sLeaf) max≤7\max \le 7, or max≤9∧min≤7\max \le 9 \land \min \le 7 Valid 1-path cover; max run ≤8\le 8 cells (Hilbert-affinity optimized).
tabZo / tabZs Two-path Z & uturn Even, max≤7\max \le 7 or (min≤7∧max≤8\min \le 7 \land \max \le 8) Valid 2-path cover for at least one colour bit b∈{0,1}b \in \{0, 1\}; max run ≤8\le 8 cells.
tabW Two-path W (wSmall) Even, min≤9,max≤27\min \le 9, \max \le 27 (~20,763 entries) Valid 2-path cover for some admissible port colouring on all InvW leaves & small exceptions; max run ≤9\le 9 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 5×45 \times 4).

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, and tabW with a memoized bounded backtracking solver minimizing straight-run length (≤6\le 6–88 cells) and returning exact Hilbert on 4×44 \times 4 and 8×88 \times 8.


9. Proved Guarantees & Implementation Checklist

Metric Definitions

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 w×hw \times h, any distinct s,ts, t Path exists ⇔\iff IpsAcc; stgFull builds it 0 diffs across 33,504 paths + 1,852 units
Exact 2D Hilbert 2k×2k2^k \times 2^k (k≥2k \ge 2), (0,0)→(2k−1,0)(0,0) \to (2^k-1, 0) Identical to classic 2D Hilbert curve Exact for all tested kk
Max Straight Run Corner (stPath) ≤12\le 12 cells 44–66 cells
One-interior (onePath) ≤17\le 17 cells 44–66 cells
Near-square rules (stgRules) ≤22\le 22 cells 44–88 cells
Long boxes (min≥20\min \ge 20, stgAll) ≤24\le 24 cells 55–88 cells
All boxes with min≥4\min \ge 4 (stgFull) ≤42\le 42 cells 44–99 cells
Turn Density / Avg Run Corner (stPath) ≥40%\ge 40\% turns (avg run <3.5< 3.5) ≈75\approx 75–81%81\% (avg ≈2.25\approx 2.25)
One-interior (onePath) ≥30%\ge 30\% turns (avg run <4.33< 4.33) ≈75\approx 75–80%80\% (avg ≈2.27\approx 2.27)
stgAll / stgRules / longPath ≥25%\ge 25\% turns (avg run <5.0< 5.0) ≈75\approx 75–80%80\% (avg ≈2.29\approx 2.29)
Narrow tiles (excTile) ≥16.7%\ge 16.7\% turns (avg run <7.0< 7.0) ≈70\approx 70–84%84\% (avg ≈2.30\approx 2.30)
Euclidean Dilation D2D_2 Corner (stPath) ≤32\le 32 (5.33×5.33\times Hilbert’s 66) 4.34.3–6.16.1
One-interior (onePath) ≤44\le 44 (7.33×7.33\times Hilbert) 4.34.3–7.57.5
Near-square (min≥4\min \ge 4, aspect ≤9/4\le 9/4) ≤56\le 56 (9.33×9.33\times Hilbert) 4.34.3–10.010.0 (squares), up to 14.114.1
All boxes & aspects (α=max/min\alpha = \max/\min) ≤94+197(1+α)\le 94 + 197(1 + \alpha) 9.59.5–23.523.5 (α∈[2.3,10]\alpha \in [2.3, 10])

Practical Implementation Checklist

  1. Integer arithmetic: All / are floor integer division; natural-number subtractions in midOut / clampN saturate at 00 (clamp explicitly in signed-integer languages).
  2. Memory management: In tCan and longPath, free failed candidate paths immediately before trying the next candidate so peak memory stays O(w⋅h)O(w \cdot h).
  3. Runtime cover validation (coverB): Verify bounds, endpoints, unit steps, uniqueness, and exact cell count on table lookups — this also filters port colours in tabW.
  4. Rebuilding this document: Run ./docs/build.sh from the repository root to regenerate all 19 SVG figures via ref/c/stgfull and compile docs/ALGORITHM.md into docs/ALGORITHM.html via pandoc --mathml (native offline HTML5 MathML; zero external dependencies).