Z80 Sudoku Solver — Canonical Source

This is the single authoritative source node for the Sudoku solver. All executable code is consolidated here. No orphan code notes are permitted.

Memory Layout

; Board base address
BOARD       EQU $A000      ; 81 bytes

; Temporary flag storage
ProgressFlag:  DEFB 0

Propagate — Constraint Sweep

; --------------------------------------------------
; Propagate
; Repeatedly sweeps board applying single-candidate fills
; OUT: Z flag set   -> contradiction
;      Z flag clear -> stable state reached
; --------------------------------------------------

Propagate:
SweepAgain:
    LD HL,BOARD
    LD B,81
    XOR A
    LD (ProgressFlag),A

CellLoop:
    LD A,(HL)
    OR A
    JR NZ,NextCell

    PUSH HL
    CALL BuildMask        ; BC = candidate mask
    JR Z,Contradiction

    ; Test single-bit: (mask & (mask-1)) == 0
    LD H,B
    LD L,C
    DEC HL
    LD A,H
    AND L
    JR NZ,NotSingle

    ; --- Bit scan placeholder (mask -> digit 1–9) ---
    ; Returns digit in A
    CALL MaskToDigit

    POP HL
    LD (HL),A

    LD A,1
    LD (ProgressFlag),A
    JR NextCellCont

NotSingle:
    POP HL

NextCellCont:
NextCell:
    INC HL
    DJNZ CellLoop

    LD A,(ProgressFlag)
    OR A
    JR NZ,SweepAgain

    RET

Contradiction:
    RET

Solve — Depth-First Search

; --------------------------------------------------
; Solve
; Full recursive solver
; --------------------------------------------------

Solve:
    CALL Propagate
    JR Z,Fail

    CALL FindMinCell
    JR Z,Solved          ; no unknown cells remain

    ; HL = cell address
    ; BC = candidate mask

BranchLoop:
    CALL NextCandidate   ; A = candidate digit, Z if none
    JR Z,Fail

    PUSH AF
    CALL PushBoard

    LD (HL),A
    CALL Solve
    JR NZ,Success

    CALL PopBoard
    POP AF
    JR BranchLoop

Success:
    POP AF
    RET

Fail:
    RET

Solved:
    RET

Planned Supporting Routines

; BuildMask     ; Compute 9-bit candidate mask in BC
; MaskToDigit   ; Convert single-bit mask -> digit 1–9
; FindMinCell   ; Locate unsolved cell with fewest candidates
; NextCandidate ; Iterate bits in mask
; PushBoard     ; Save 81-byte board frame
; PopBoard      ; Restore previous board state