|
| 1 | +from __future__ import annotations |
| 2 | +""" |
| 3 | +State-of-the-art canonicalization for Sudoku puzzles. |
| 4 | +
|
| 5 | +Maps isomorphic puzzles to a single 81-char canonical form using: |
| 6 | + • Dihedral symmetries D4 (8 transforms) |
| 7 | + • Band (row bands) and stack (column stacks) permutations (3! each) |
| 8 | + • Row swaps within each band and column swaps within each stack (3! for each band/stack) |
| 9 | + • Greedy digit relabeling (first-appearance maps to 1..9) |
| 10 | +
|
| 11 | +Total variants explored per grid: 8 × (3!)^4 = 10,368 — acceptable for CLI/tests. |
| 12 | +""" |
| 13 | +from itertools import permutations |
| 14 | +from typing import List, Sequence, Tuple |
| 15 | + |
| 16 | +from .api import Grid |
| 17 | + |
| 18 | +# --------- Dihedral transforms over 9x9 grids (D4) ---------- |
| 19 | + |
| 20 | +def _rot90(g: Grid) -> Grid: |
| 21 | + return [[g[9 - 1 - c][r] for c in range(9)] for r in range(9)] |
| 22 | + |
| 23 | + |
| 24 | +def _rot180(g: Grid) -> Grid: |
| 25 | + return [[g[9 - 1 - r][9 - 1 - c] for c in range(9)] for r in range(9)] |
| 26 | + |
| 27 | + |
| 28 | +def _rot270(g: Grid) -> Grid: |
| 29 | + return [[g[c][9 - 1 - r] for c in range(9)] for r in range(9)] |
| 30 | + |
| 31 | + |
| 32 | +def _flip_h(g: Grid) -> Grid: |
| 33 | + # horizontal flip (mirror over vertical axis) |
| 34 | + return [[g[r][9 - 1 - c] for c in range(9)] for r in range(9)] |
| 35 | + |
| 36 | + |
| 37 | +def _flip_v(g: Grid) -> Grid: |
| 38 | + # vertical flip (mirror over horizontal axis) |
| 39 | + return [g[9 - 1 - r][:] for r in range(9)] |
| 40 | + |
| 41 | + |
| 42 | +def _flip_main_diag(g: Grid) -> Grid: |
| 43 | + # transpose over main diagonal |
| 44 | + return [[g[c][r] for c in range(9)] for r in range(9)] |
| 45 | + |
| 46 | + |
| 47 | +def _flip_anti_diag(g: Grid) -> Grid: |
| 48 | + # reflect over anti-diagonal (r,c) -> (8-c,8-r) |
| 49 | + return [[g[9 - 1 - c][9 - 1 - r] for c in range(9)] for r in range(9)] |
| 50 | + |
| 51 | + |
| 52 | +_TRANSFORMS = ( |
| 53 | + lambda x: x, |
| 54 | + _rot90, |
| 55 | + _rot180, |
| 56 | + _rot270, |
| 57 | + _flip_h, |
| 58 | + _flip_v, |
| 59 | + _flip_main_diag, |
| 60 | + _flip_anti_diag, |
| 61 | +) |
| 62 | + |
| 63 | +# --------- Permutations for bands/stacks and inner rows/cols ---------- |
| 64 | + |
| 65 | +_PERM3 = list(permutations((0, 1, 2))) # 6 perms |
| 66 | + |
| 67 | + |
| 68 | +def _cell_char(value: int) -> str: |
| 69 | + if value == 0: |
| 70 | + return "." |
| 71 | + if isinstance(value, str): |
| 72 | + return value if value not in {"0", "-"} else "." |
| 73 | + return str(value) |
| 74 | + |
| 75 | + |
| 76 | +def _canonical_band_stack( |
| 77 | + grid_chars: Sequence[Sequence[str]], |
| 78 | + band_perm: Tuple[int, int, int], |
| 79 | + stack_perm: Tuple[int, int, int], |
| 80 | + best: str | None, |
| 81 | +) -> str | None: |
| 82 | + best_local = best |
| 83 | + chosen_row_perms: dict[int, Tuple[int, int, int]] = {} |
| 84 | + chosen_col_perms: dict[int, Tuple[int, int, int]] = {} |
| 85 | + mapping: dict[str, str] = {} |
| 86 | + out_chars: List[str] = [] |
| 87 | + next_digit = ord("1") |
| 88 | + cmp_state = 0 |
| 89 | + |
| 90 | + def rollback(inserted: List[str], saved_len: int, saved_next: int, saved_cmp: int) -> None: |
| 91 | + nonlocal next_digit, cmp_state |
| 92 | + del out_chars[saved_len:] |
| 93 | + next_digit = saved_next |
| 94 | + cmp_state = saved_cmp |
| 95 | + for key in reversed(inserted): |
| 96 | + mapping.pop(key, None) |
| 97 | + |
| 98 | + def dfs(block_idx: int) -> None: |
| 99 | + nonlocal best_local, next_digit, cmp_state |
| 100 | + if block_idx == 9: |
| 101 | + candidate = "".join(out_chars) |
| 102 | + if best_local is None or candidate < best_local: |
| 103 | + best_local = candidate |
| 104 | + return |
| 105 | + |
| 106 | + band_idx = block_idx // 3 |
| 107 | + stack_idx = block_idx % 3 |
| 108 | + band = band_perm[band_idx] |
| 109 | + stack = stack_perm[stack_idx] |
| 110 | + |
| 111 | + row_options = ( |
| 112 | + (chosen_row_perms[band],) |
| 113 | + if band in chosen_row_perms |
| 114 | + else _PERM3 |
| 115 | + ) |
| 116 | + col_options = ( |
| 117 | + (chosen_col_perms[stack],) |
| 118 | + if stack in chosen_col_perms |
| 119 | + else _PERM3 |
| 120 | + ) |
| 121 | + |
| 122 | + for row_perm in row_options: |
| 123 | + assigned_row = False |
| 124 | + if band not in chosen_row_perms: |
| 125 | + chosen_row_perms[band] = row_perm |
| 126 | + assigned_row = True |
| 127 | + for col_perm in col_options: |
| 128 | + assigned_col = False |
| 129 | + if stack not in chosen_col_perms: |
| 130 | + chosen_col_perms[stack] = col_perm |
| 131 | + assigned_col = True |
| 132 | + |
| 133 | + saved_len = len(out_chars) |
| 134 | + saved_next = next_digit |
| 135 | + saved_cmp = cmp_state |
| 136 | + inserted: List[str] = [] |
| 137 | + pruned = False |
| 138 | + |
| 139 | + for r_local in row_perm: |
| 140 | + row = grid_chars[band * 3 + r_local] |
| 141 | + for c_local in col_perm: |
| 142 | + ch = row[stack * 3 + c_local] |
| 143 | + if ch == ".": |
| 144 | + mapped = "." |
| 145 | + else: |
| 146 | + mapped = mapping.get(ch) |
| 147 | + if mapped is None: |
| 148 | + mapped = chr(next_digit) |
| 149 | + mapping[ch] = mapped |
| 150 | + inserted.append(ch) |
| 151 | + if next_digit < ord("9"): |
| 152 | + next_digit += 1 |
| 153 | + out_chars.append(mapped) |
| 154 | + if best_local is not None and cmp_state == 0: |
| 155 | + best_char = best_local[len(out_chars) - 1] |
| 156 | + if mapped > best_char: |
| 157 | + pruned = True |
| 158 | + break |
| 159 | + if mapped < best_char: |
| 160 | + cmp_state = -1 |
| 161 | + if pruned: |
| 162 | + break |
| 163 | + |
| 164 | + if not pruned: |
| 165 | + dfs(block_idx + 1) |
| 166 | + |
| 167 | + rollback(inserted, saved_len, saved_next, saved_cmp) |
| 168 | + |
| 169 | + if assigned_col: |
| 170 | + chosen_col_perms.pop(stack, None) |
| 171 | + |
| 172 | + if pruned and best_local is not None and cmp_state == 0: |
| 173 | + # If pruning occurred due to mapped > best prefix, remaining column perms |
| 174 | + # in this branch are unlikely to improve; continue to next col perm. |
| 175 | + pass |
| 176 | + |
| 177 | + if assigned_row: |
| 178 | + chosen_row_perms.pop(band, None) |
| 179 | + |
| 180 | + dfs(0) |
| 181 | + return best_local |
| 182 | + |
| 183 | + |
| 184 | +# --------- Public API (full canon) ---------- |
| 185 | + |
| 186 | + |
| 187 | +def canonical_form(grid: Grid) -> str: |
| 188 | + """ |
| 189 | + Return the lexicographically smallest normalized string among all: |
| 190 | + - D4 dihedral transforms |
| 191 | + - Band and stack permutations |
| 192 | + - Row swaps within each band, column swaps within each stack |
| 193 | + Each candidate is normalized by greedy digit relabeling before compare. |
| 194 | + """ |
| 195 | + best: str | None = None |
| 196 | + for tf in _TRANSFORMS: |
| 197 | + g1 = tf(grid) |
| 198 | + grid_chars = [[_cell_char(cell) for cell in row] for row in g1] |
| 199 | + for band_perm in _PERM3: |
| 200 | + for stack_perm in _PERM3: |
| 201 | + cand = _canonical_band_stack(grid_chars, band_perm, stack_perm, best) |
| 202 | + if cand is not None and (best is None or cand < best): |
| 203 | + best = cand |
| 204 | + assert best is not None |
| 205 | + return best |
| 206 | + |
| 207 | + |
| 208 | +__all__ = ["canonical_form"] |
0 commit comments