← blog  /  tools

Samurai sudoku generator in Python: one answer for the board is not enough

2026-11-26  ·  6 min read  ·  tools

A samurai sudoku is five grids that share corner boxes. A generator that only asks for one answer for the whole board left boards where none of the five grids had one answer on its own. Asking it of every grid costs about 14 more starting digits and made the generator 12 times faster.

A samurai sudoku is five 9 x 9 sudoku grids on a 21 x 21 board: one in the middle and four at the corners, each corner grid sharing one 3 x 3 box with the middle one. That makes 5 x 81 - 4 x 9 = 369 squares. A square in a shared box belongs to two grids, so it has 32 other squares it must differ from instead of 20.

A generator works as for one sudoku: fill the whole board, then take digits away in random order and keep a digit whenever taking it away would allow a second answer. On 1 November 2026 we made 10 boards that way, and 10 more with one extra rule.

The short version#

  • One answer for the board: 97.7 starting digits on average (92 to 102). But in none of the 10 boards did any of the five grids have one answer from its own digits. Every grid could be finished only with help from the shared boxes.
  • One answer for every grid too: 112.1 starting digits on average (109 to 116), about 25 a grid, and all five grids of all 10 boards had one answer on their own.
  • The stricter board was faster to make: 2.2 s a board against 27.5 s. With more digits left, every check is quick; a sparse board makes the counter search for a long time.

The code#

Samurai sudoku: the board, a solution counter and a generatorpython
import random

CORNERS = {"top left": (0, 0), "top right": (0, 12), "middle": (6, 6), "bottom left": (12, 0), "bottom right": (12, 12)}


def grid_units(top, left):
    """The 27 rows, columns and boxes of the 9 x 9 grid whose top left square is (top, left)."""
    rows = [[(top + r, left + c) for c in range(9)] for r in range(9)]
    cols = [[(top + r, left + c) for r in range(9)] for c in range(9)]
    boxes = [[(top + R + r, left + C + c) for r in range(3) for c in range(3)] for R in (0, 3, 6) for C in (0, 3, 6)]
    return rows + cols + boxes


def board(grids=CORNERS):
    """The squares of the board, and every square's peers: the squares it shares a row, column or box with."""
    units = [u for top, left in grids.values() for u in grid_units(top, left)]
    squares = sorted({sq for u in units for sq in u})
    peers = {sq: set() for sq in squares}
    for u in units:
        for sq in u:
            peers[sq] |= set(u)
    return squares, {sq: sorted(p - {sq}) for sq, p in peers.items()}


SQUARES, PEERS = board()


def solve(given, squares=SQUARES, peers=PEERS, stop=2, rng=None, limit=200000):
    """Count the boards that fit the digits in `given` ({square: digit}) up to `stop`, square with the fewest
    options first. With `rng`, digits go in random order and the first board found is returned instead.
    Gives up after `limit` steps (returns None)."""
    index = {sq: i for i, sq in enumerate(squares)}
    near = [[index[p] for p in peers[sq]] for sq in squares]
    value = [0] * len(squares)
    blocked = [[0] * 10 for _ in squares]          # blocked[i][d]: peers of square i that hold digit d
    open_ = set(range(len(squares)))

    def put(i, d):
        value[i] = d
        open_.discard(i)
        for p in near[i]:
            blocked[p][d] += 1

    def take(i, d):
        value[i] = 0
        open_.add(i)
        for p in near[i]:
            blocked[p][d] -= 1
    for sq, d in given.items():
        if blocked[index[sq]][d]:
            return 0                                # two equal digits see each other
        put(index[sq], d)
    found, steps = [], [0]

    def go():
        steps[0] += 1
        if steps[0] > limit:
            raise TimeoutError
        best, options = None, None
        for i in open_:
            b = blocked[i]
            opts = [d for d in range(1, 10) if not b[d]]
            if best is None or len(opts) < len(options):
                best, options = i, opts
                if len(opts) <= 1:
                    break
        if best is None:
            found.append({squares[i]: value[i] for i in range(len(squares))})
            return len(found) >= stop
        if rng:
            rng.shuffle(options)
        for d in options:
            put(best, d)
            if go():
                return True
            take(best, d)
        return False

    try:
        go()
    except TimeoutError:
        return None
    return found[0] if rng else len(found)


GRIDS = {name: board({name: corner}) for name, corner in CORNERS.items()}


def alone(given):
    """For each of the five grids: does it have one answer from its own starting digits, ignoring the others?"""
    return {name: solve({sq: d for sq, d in given.items() if sq in peers}, squares, peers) == 1
            for name, (squares, peers) in GRIDS.items()}


def make(rng=random, each_grid=True, limit=20000):
    """A full board, then take digits away in random order. A digit stays if taking it away gives the board a
    second answer, or (with `each_grid`) gives one of the five grids a second answer on its own. A check that
    runs past `limit` steps counts as a second answer: the digit stays. Returns the board, the starting digits and
    how many checks gave up."""
    full = None
    while not full:
        full = solve({}, stop=1, rng=rng, limit=limit)
    given, gave_up = dict(full), 0
    for sq in rng.sample(SQUARES, len(SQUARES)):
        digit = given.pop(sq)
        counts = [solve(given, limit=limit)]
        if counts[0] == 1 and each_grid:
            counts += [solve({s: d for s, d in given.items() if s in peers}, squares, peers, limit=limit)
                       for squares, peers in GRIDS.values() if sq in peers]
        gave_up += None in counts
        if any(c != 1 for c in counts):
            given[sq] = digit
    return full, given, gave_up
Run itpython
full, given, gave_up = make(random.Random(1))
print(len(given), "starting digits |", {name: ok for name, ok in alone(given).items()}, "| answers:", solve(given))

It made a board with 107 starting digits, one answer for the whole board, and one answer for each of the five grids.

The board as one puzzle#

board() lists the rows, columns and boxes of the five grids and gives each square its peers. The shared boxes need nothing special: their squares appear in the units of two grids, so they get the peers of both. solve() then treats the 369 squares as one puzzle. It keeps, for every square, how many of its peers hold each digit, so it can see a square's options without looking at all its peers again, and it fills the square with the fewest options first.

A sparse board can take the counter a long time to prove that it has only one answer. solve() gives up after limit steps, and make() then keeps the digit, as if a second answer had been found. On the boards with the board-only rule, 19.4 checks a board gave up on average, so those boards keep a few digits they might have lost; with the rule for every grid, none gave up.

Why every grid should have one answer#

With only the board rule, a grid kept as few as 11 starting digits. Such a grid has many answers on its own, so a solver has to bring digits in from a neighbouring grid through a shared box before it can finish it. That makes a joined-up puzzle, which may be what you want. For a book where a reader can start on any grid, ask each grid for one answer on its own; then no grid depends on another.

Books#

Our samurai sudoku book maker checks both: a second program, written apart from the one that makes the puzzles, counts the solutions of all 369 squares at once and finds exactly one, the one printed at the back, and each of the five grids has exactly one solution from its own starting digits. Easy and medium boards are solved square by square with singles; hard ones need locked candidates or pairs, and the solver confirms that singles alone do not finish them. Each book is checked against KDP's paperback specs before you can download it. One samurai sudoku book costs 500 credits, from $3.30 in the big pack.

written