← blog  /  tools

Killer sudoku generator in Python: cut the cages until logic solves it

2026-11-25  ·  13 min read  ·  tools

Random cages over a finished grid had exactly one answer in 2 of 60 tries, and logic alone solved none. Cutting cages until logic solves the puzzle works, and the rule of 45 takes it from 218 grids a puzzle to 9.

A killer sudoku has no starting digits. Dashed lines cut the grid into cages, the digits in a cage add up to the small number in its corner, and no digit repeats in a cage. Every row, column and 3 x 3 box still holds 1 to 9 once. A generator needs a finished grid, cages over it, and proof that the cages allow only that grid.

On 21 November 2026 we built one in Python. A first try drew random cages and checked them with a plain search, as in our sudoku generator post; the search could not decide most of them. This one lets deduction decide instead.

The short version#

  • Random cages almost never work. We grew cages of up to 5 squares at random over 60 random grids: 3.3 squares a cage and 2.1 one-square cages on average. Deduction alone solved none of them. Knuth's Algorithm X found two answers or more for 54, exactly one for 2, and had not finished after 20,000 steps on 4.
  • Cut the cages until logic solves it. While deduction is stuck, cut an unsolved cage of 4 squares or more in two. When nothing is left to cut, start again on a new grid; a grid whose random cages include more than two one-square cages is skipped.
  • The rule of 45 does most of the work. Every row, column and box adds up to 45, so the squares a unit has outside its whole cages add up to 45 minus their totals. Without that rule the generator tried 218 grids for a puzzle on average (728 at most) and took about 2.4 s (median); with it, 8.6 grids (24 at most) and about 0.2 s.
  • Every puzzle is checked twice. For all 40 puzzles, 20 made each way, Algorithm X, with no deduction at all, found exactly one answer, and it was the grid the cages were cut from. It took 0.4 s or less each.

The code#

A killer sudoku generator: random cages, deduction with the rule of 45, cuts, and an exact countpython
import random
from itertools import combinations, permutations

BOX = [[(r // 3) * 3 + c // 3 for c in range(9)] for r in range(9)]
UNITS = ([[(r, c) for c in range(9)] for r in range(9)] + [[(r, c) for r in range(9)] for c in range(9)]
         + [[(r, c) for r in range(9) for c in range(9) if BOX[r][c] == b] for b in range(9)])
ALL = sum(1 << d for d in range(1, 10))
ONE = {1 << d: d for d in range(1, 10)}          # a square with one candidate left: bit -> digit


def full_grid(rng=random):
    """A random finished sudoku: fill square by square, digits in random order, back up on a dead end."""
    grid = [[0] * 9 for _ in range(9)]

    def go(i):
        if i == 81:
            return True
        r, c = divmod(i, 9)
        used = set(grid[r]) | {grid[y][c] for y in range(9)} | {
            grid[y][x] for y in range(9) for x in range(9) if BOX[y][x] == BOX[r][c]}
        for d in rng.sample(range(1, 10), 9):
            if d not in used:
                grid[r][c] = d
                if go(i + 1):
                    return True
        grid[r][c] = 0
        return False

    go(0)
    return grid


def cages(grid, rng=random, most=5):
    """Cut the grid into connected cages of up to `most` squares with no digit twice: grow each cage from the first
    free square to a random size; a cage that cannot grow stays a single square (which gives its digit away)."""
    free, out = {(r, c) for r in range(9) for c in range(9)}, []
    while free:
        cell = min(free)
        cage, size = [cell], rng.randint(2, most)
        free.discard(cell)
        while len(cage) < size:
            digits = {grid[r][c] for r, c in cage}
            nexts = [(r + dr, c + dc) for r, c in cage for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0))
                     if (r + dr, c + dc) in free and grid[r + dr][c + dc] not in digits]
            if not nexts:
                break
            cell = rng.choice(nexts)
            cage.append(cell)
            free.discard(cell)
        out.append((cage, sum(grid[r][c] for r, c in cage)))
    return out


def logic(puzzle, rule45=True):
    """Candidates left (a bit mask per square) after deduction alone, or None on a contradiction. Every group of
    different digits with a known total (each cage; with the rule of 45 also the squares of a row, column or box
    left over after its whole cages, which add up to 45 minus their totals) keeps only the digit sets that can
    still be placed; a square keeps only digits of those sets; a solved square leaves its row, column, box and cage;
    a digit with one place left in a row, column or box goes there."""
    groups = [(cells, total) for cells, total in puzzle]
    if rule45:
        for unit in UNITS:
            whole = [(cells, t) for cells, t in puzzle if set(cells) <= set(unit)]
            rest = [x for x in unit if not any(x in cells for cells, t in whole)]
            if 0 < len(rest) < 9:
                groups.append((rest, 45 - sum(t for cells, t in whole)))
    sets = [[sum(1 << d for d in s) for s in combinations(range(1, 10), len(cells)) if sum(s) == t]
            for cells, t in groups]
    peers = {x: set() for x in [(r, c) for r in range(9) for c in range(9)]}
    for unit in UNITS + [cells for cells, t in puzzle]:
        for x in unit:
            peers[x].update(y for y in unit if y != x)
    cand = {x: ALL for x in peers}
    changed = True
    while changed:
        changed = False
        for (cells, t), options in zip(groups, sets):
            fixed = sum(cand[x] for x in cells if cand[x] in ONE)
            union = 0
            for s in options:
                if fixed & s == fixed and all(cand[x] & s for x in cells):
                    reach = 0
                    for x in cells:
                        reach |= cand[x] & s
                    if reach == s:                    # every digit of the set still has a square
                        union |= s
            for x in cells:
                if cand[x] & union != cand[x]:
                    cand[x] &= union
                    changed = True
                    if not cand[x]:
                        return None
        for x, m in cand.items():
            if m in ONE:
                for y in peers[x]:
                    if cand[y] & m:
                        cand[y] &= ~m
                        changed = True
                        if not cand[y]:
                            return None
        for unit in UNITS:
            for d in range(1, 10):
                places = [x for x in unit if cand[x] & (1 << d)]
                if not places:
                    return None
                if len(places) == 1 and cand[places[0]] != 1 << d:
                    cand[places[0]] = 1 << d
                    changed = True
    return cand


def connected(cells):
    seen, todo = {cells[0]}, [cells[0]]
    while todo:
        r, c = todo.pop()
        for x in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if x in cells and x not in seen:
                seen.add(x)
                todo.append(x)
    return len(seen) == len(cells)


def split(cells, rng=random, tries=20):
    """Cut a cage of 4 squares or more into two connected parts of 2 squares or more, or None."""
    for _ in range(tries):
        size, part = rng.randint(2, len(cells) - 2), [rng.choice(cells)]
        while len(part) < size:
            nexts = [(r + dr, c + dc) for r, c in part for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0))
                     if (r + dr, c + dc) in cells and (r + dr, c + dc) not in part]
            if not nexts:
                break
            part.append(rng.choice(nexts))
        rest = [x for x in cells if x not in part]
        if len(part) == size and connected(rest):
            return part, rest
    return None


def make(rng=random, most=5, singles=2, rule45=True, tries=1000):
    """A finished grid and cages that logic alone solves, with at most `singles` one-square cages. While logic is
    stuck, cut an unsolved cage of 4 squares or more in two; when none is left to cut, start again on a new grid.
    Returns (grid, puzzle, grids tried, cuts made)."""
    for k in range(1, tries + 1):
        grid = full_grid(rng)
        puzzle, cuts = cages(grid, rng, most), 0
        while sum(len(cells) == 1 for cells, t in puzzle) <= singles:
            cand = logic(puzzle, rule45)
            if all(m in ONE for m in cand.values()):
                return grid, puzzle, k, cuts
            stuck = [i for i, (cells, t) in enumerate(puzzle) if len(cells) >= 4 and any(cand[x] not in ONE for x in cells)]
            rng.shuffle(stuck)
            parts = next(((i, p) for i in stuck for p in [split(puzzle[i][0], rng)] if p), None)
            if parts is None:
                break
            i, (a, b) = parts
            puzzle[i:i + 1] = [(p, sum(grid[r][c] for r, c in p)) for p in (a, b)]
            cuts += 1
    raise RuntimeError("no puzzle in %d grids" % tries)


def count_answers(puzzle, stop=2, limit=None):
    """How many finished grids fit the cages (up to `stop`), by Knuth's Algorithm X with no deduction at all: one
    choice per way to fill a cage (its digit sets in every order), and each choice covers its squares and its
    digits in their rows, columns and boxes. Returns (count, first answer), or (None, None) after `limit` steps."""
    choices = {}
    for i, (cells, total) in enumerate(puzzle):
        for s in combinations(range(1, 10), len(cells)):
            if sum(s) == total:
                for digits in permutations(s):
                    choices[i, digits] = [k for (r, c), d in zip(cells, digits) for k in
                                          (("square", r, c), ("row", r, d), ("col", c, d), ("box", BOX[r][c], d))]
    cols = {}
    for choice, keys in choices.items():
        for k in keys:
            cols.setdefault(k, set()).add(choice)
    if len(cols) < 324:
        return 0, None
    found, first, path, steps = [0], [None], [], [0]

    def take(choice):
        removed = []
        for j in choices[choice]:
            for other in cols[j]:
                for k in choices[other]:
                    if k != j:
                        cols[k].discard(other)
            removed.append(cols.pop(j))
        return removed

    def give_back(choice, removed):
        for j in reversed(choices[choice]):
            cols[j] = removed.pop()
            for other in cols[j]:
                for k in choices[other]:
                    if k != j:
                        cols[k].add(other)

    def go():
        steps[0] += 1
        if limit and steps[0] > limit:
            raise TimeoutError
        if not cols:
            found[0] += 1
            first[0] = first[0] or list(path)
            return found[0] >= stop
        j = min(cols, key=lambda k: len(cols[k]))
        for choice in list(cols[j]):
            removed = take(choice)
            path.append(choice)
            done = go()
            path.pop()
            give_back(choice, removed)
            if done:
                return True
        return False

    try:
        go()
    except TimeoutError:
        return None, None
    grid = [[0] * 9 for _ in range(9)]
    for i, digits in first[0] or []:
        for (r, c), d in zip(puzzle[i][0], digits):
            grid[r][c] = d
    return found[0], grid if first[0] else None
Run itpython
grid, puzzle, tried, cuts = make(random.Random(4))
print(len(puzzle), "cages, sizes:", sorted(len(cells) for cells, t in puzzle))
print("grids tried:", tried, "| cuts:", cuts, "| answers:", count_answers(puzzle)[0])
names = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
where = {x: names[i] for i, (cells, t) in enumerate(puzzle) for x in cells}
for r in range(9):
    print("".join(where[r, c] for c in range(9)))
totals = [f"{names[i]}={t}" for i, (cells, t) in enumerate(puzzle)]
for k in range(0, len(totals), 9):
    print(" ".join(totals[k:k + 9]))

With that seed it tried 9 grids and made 9 cuts. It printed 35 cages: 2 of one square, 20 of two and 13 of three. Each letter below is a cage, and the totals follow the map. Algorithm X found one answer.

Cages and totalstext
accdffeeg
aiiddjjlg
abimnkklh
pbqmnrrth
poounwsth
xvuuzwsAA
xvBCzDDAE
yyBCCGGEE
yHBIIIGFF
a=14 b=9 c=10 d=13 e=12 f=9 g=12 h=11 i=16
j=4 k=12 l=6 m=8 n=17 o=11 p=9 q=7 r=15
s=11 t=11 u=19 v=4 w=10 x=12 y=18 z=13 A=12
B=10 C=15 D=11 E=14 F=15 G=18 H=9 I=8

How logic decides#

logic() never guesses. It keeps, for every square, the digits that can still go there, and repeats four steps until nothing changes:

  1. A cage keeps only the sets of different digits that make its total and can still be placed. A cage of 2 squares with a total of 4 can only hold 1 and 3, so both squares lose every other digit.
  2. With the rule of 45, each row, column and box adds one more group of this kind: its squares outside the cages that lie wholly inside it, with 45 minus those cages' totals.
  3. A solved square takes its digit out of its row, column, box and cage.
  4. A digit with only one place left in a row, column or box goes there.

Each step removes only digits that cannot be there. So when every square is down to one digit, that grid is the only answer, and no search is needed to prove it.

count_answers() checks it from the other side. It knows nothing of deduction: each way to fill a cage, its digits in every order, is one choice, and Algorithm X picks choices so that every square gets one digit and every row, column and box gets each digit once. On the puzzles make() returns it ends quickly, because few choices fit. On random cages it can wander: we stopped it at 20,000 steps, and 4 of the 60 were still open there.

Two random cage sets had one answer#

In 2 of the 60 random cage sets, Algorithm X found exactly one answer, yet deduction could not finish them. Their solution is unique, but a solver who knows only the four steps above cannot reach it without guessing. A book should not print such a puzzle. That is why the generator asks logic, not the count, whether a puzzle is done, and keeps the count as the second check.

The catch: small cages#

Cutting makes cages smaller. The random cages started at 3.3 squares a cage on average; the finished puzzles had 2.4 (without the rule of 45) or 2.5 (with it), and the one above has no cage of more than 3 squares. Small cages give more away, so these puzzles are on the easy side. To keep cages of 4 and 5 squares, the logic has to know more: the rule of 45 on two or three rows side by side, squares that stick out of a row or box, pairs and locked candidates. The more it knows, the fewer cuts it needs.

A whole book, not one grid#

Our killer sudoku book maker solves every puzzle again step by step from the cage totals alone, with no guessing. Easy puzzles need only the cages and the usual sudoku steps; medium ones may use the rule of 45 on a row, column or box; every hard one needs more than the basics, and about a third of them need the rule of 45 on several rows, columns or boxes at once. A second program, written apart from the one that makes the puzzles, tries every way to fill every cage from its total and finds exactly one finished grid, the one printed in the answers.

Every cage is one connected group of up to 5 squares with no digit twice, and a puzzle has at most two one-square cages (one at medium and hard). Each book is checked against KDP's paperback specs before you can download it. One killer sudoku book costs 500 credits, from $3.30 in the big pack.

written