Skip to content
Python project #19Advanced

Sudoku Solver

Solve any Sudoku with constraint propagation (naked and hidden singles) plus a most-constrained-cell backtracking search, and reject invalid puzzles.

Estimated time
~5 hours to build
Files
4 files · 306 lines
Technologies
Python 3, Sets and dictionaries, Recursion

Introduction

Sudoku is a classic constraint-satisfaction problem. Simple logic solves easy puzzles outright; hard ones need search. Combining both — propagate constraints after every guess and always guess in the most constrained cell — solves even the hardest puzzles in a fraction of a second.

Problem statement

Read one or more puzzles, separated by blank lines, as nine rows or a single 81-character line, with '.' or '0' for blanks and optional '#' title lines. Reject puzzles with the wrong size, invalid characters or duplicate givens. Solve each puzzle, print the grid with box separators and report how many cells were solved by propagation alone and how many guesses the search needed, or say that no solution exists.

Objectives

  • Represent candidates with sets
  • Implement constraint propagation with mutual recursion
  • Write a backtracking search with the MRV heuristic
  • Precompute units and peers for speed

Features

  • Flexible puzzle input with titles
  • Validation of size, characters and duplicate givens
  • Naked-single and hidden-single propagation
  • Backtracking on the cell with fewest candidates
  • Statistics on propagation and guesses

Concepts demonstrated

  • Constraint satisfaction
  • Propagation
  • Backtracking
  • Heuristics

System architecture

UNITS (rows, columns, boxes) and PEERS are computed once. assign removes every other candidate from a cell; eliminate removes one, then applies the two rules: a cell with one candidate removes it from its peers, and a digit with only one place in a unit is assigned there. A Contradiction exception signals a dead end. search copies the candidate map, guesses in the cell with the fewest candidates and recurses.

Folder structure

TextProject tree
sudoku-solver/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

138 lines
Pythonmain.py
"""Sudoku Solver: constraint propagation plus backtracking search.
Input: one or more puzzles separated by blank lines. A puzzle is nine lines of nine
characters or a single line of 81; digits are givens and '.' or '0' are blanks.
A line starting with '#' names the puzzle that follows.
"""
import sys
import time
DIGITS = set("123456789")
ROWS = [[(r, c) for c in range(9)] for r in range(9)]
COLS = [[(r, c) for r in range(9)] for c in range(9)]
BOXES = [[(br + r, bc + c) for r in range(3) for c in range(3)] for br in (0, 3, 6) for bc in (0, 3, 6)]
UNITS = ROWS + COLS + BOXES
PEERS = {(r, c): {cell for unit in UNITS if (r, c) in unit for cell in unit} - {(r, c)} for r in range(9) for c in range(9)}
class Contradiction(Exception):
"""Raised when a cell loses all its candidates."""
def parse(lines: list[str]) -> dict[tuple[int, int], str]:
text = "".join("".join(line.split()) for line in lines).replace("0", ".")
if len(text) != 81 or any(ch not in DIGITS | {"."} for ch in text):
raise ValueError(f"a puzzle needs 81 cells of 1-9, '.' or '0' (got {len(text)})")
return {(i // 9, i % 9): ch for i, ch in enumerate(text) if ch != "."}
def check_givens(givens: dict[tuple[int, int], str]) -> None:
for cell, digit in givens.items():
for peer in PEERS[cell]:
if givens.get(peer) == digit:
r, c = sorted([cell, peer])[1]
raise ValueError(f"digit {digit} appears twice (row {r + 1}, column {c + 1} conflicts)")
def assign(cands: dict, cell: tuple[int, int], digit: str) -> None:
for other in cands[cell] - {digit}:
eliminate(cands, cell, other)
def eliminate(cands: dict, cell: tuple[int, int], digit: str) -> None:
if digit not in cands[cell]:
return
cands[cell] = cands[cell] - {digit}
if not cands[cell]:
raise Contradiction
if len(cands[cell]) == 1: # naked single: remove it from all peers
only = next(iter(cands[cell]))
for peer in PEERS[cell]:
eliminate(cands, peer, only)
for unit in UNITS: # hidden single: the only place for a digit in a unit
if cell in unit:
places = [c for c in unit if digit in cands[c]]
if not places:
raise Contradiction
if len(places) == 1 and len(cands[places[0]]) > 1:
assign(cands, places[0], digit)
def search(cands: dict, stats: dict) -> dict | None:
if all(len(v) == 1 for v in cands.values()):
return cands
cell = min((c for c in cands if len(cands[c]) > 1), key=lambda c: (len(cands[c]), c)) # most constrained cell
for digit in sorted(cands[cell]):
stats["guesses"] += 1
trial = dict(cands)
try:
assign(trial, cell, digit)
except Contradiction:
continue
result = search(trial, stats)
if result:
return result
return None
def solve(givens: dict) -> tuple[dict | None, dict]:
cands = {(r, c): set(DIGITS) for r in range(9) for c in range(9)}
stats = {"guesses": 0}
try:
for cell, digit in givens.items():
assign(cands, cell, digit)
except Contradiction:
return None, stats
stats["after_propagation"] = sum(len(v) == 1 for v in cands.values())
return search(cands, stats), stats
def show(grid: dict) -> None:
for r in range(9):
if r in (3, 6):
print(" ------+-------+------")
row = [next(iter(grid[(r, c)])) if isinstance(grid[(r, c)], set) else grid[(r, c)] for c in range(9)]
print(" " + " | ".join(" ".join(row[i:i + 3]) for i in (0, 3, 6)))
def puzzles(text: str) -> list[tuple[str, list[str]]]:
result, name, block = [], None, []
for line in text.splitlines() + [""]:
if line.startswith("#"):
name = line[1:].strip()
elif line.strip():
block.append(line)
elif block:
result.append((name or f"Puzzle {len(result) + 1}", block))
name, block = None, []
return result
def main() -> None:
found = puzzles(sys.stdin.read())
if not found:
print("No puzzles found.")
return
for name, lines in found:
print(f"== {name} ==")
try:
givens = parse(lines)
check_givens(givens)
except ValueError as error:
print(f" Invalid puzzle: {error}\n")
continue
start = time.perf_counter()
solution, stats = solve(givens)
elapsed = time.perf_counter() - start
print(f" Givens: {len(givens)}, solved by propagation alone: {stats.get('after_propagation', 0)} cells")
if solution is None:
print(" No solution exists.\n")
continue
show(solution)
method = "logic only" if stats["guesses"] == 0 else f"{stats['guesses']} guess(es) during search"
print(f" Solved with {method}.{'' if elapsed < 5 else ' (slow!)'}\n")
if __name__ == "__main__":
main()

What each file does

main.py
Units and peers, the propagation functions, the backtracking search, input parsing and output.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
== Easy (logic only) ==
Givens: 30, solved by propagation alone: 81 cells
5 3 4 | 6 7 8 | 9 1 2
6 7 2 | 1 9 5 | 3 4 8
1 9 8 | 3 4 2 | 5 6 7
------+-------+------
8 5 9 | 7 6 1 | 4 2 3
4 2 6 | 8 5 3 | 7 9 1
7 1 3 | 9 2 4 | 8 5 6
------+-------+------
9 6 1 | 5 3 7 | 2 8 4
2 8 7 | 4 1 9 | 6 3 5
3 4 5 | 2 8 6 | 1 7 9
Solved with logic only.
== Hard (needs search) ==
Givens: 17, solved by propagation alone: 20 cells
4 1 7 | 3 6 9 | 8 2 5
6 3 2 | 1 5 8 | 9 4 7
9 5 8 | 7 2 4 | 3 1 6
------+-------+------
8 2 5 | 4 3 7 | 1 6 9
7 9 1 | 5 8 6 | 4 3 2
3 4 6 | 9 1 2 | 7 5 8
------+-------+------
2 8 9 | 6 4 3 | 5 7 1
5 7 3 | 2 9 1 | 6 8 4
1 6 4 | 8 7 5 | 2 9 3
Solved with 25 guess(es) during search.
== Broken (two 5s in the first row) ==
Invalid puzzle: digit 5 appears twice (row 1, column 2 conflicts)
== Too short ==
Invalid puzzle: a puzzle needs 81 cells of 1-9, '.' or '0' (got 9)
Input
# Easy (logic only)
53..7....
6..195...
.98....6.
8...6...3
4..8.3..1
7...2...6
.6....28.
...419..5
....8..79

# Hard (needs search)
4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......

# Broken (two 5s in the first row)
55..7....
6..195...
.98....6.
8...6...3
4..8.3..1
7...2...6
.6....28.
...419..5
....8..79

# Too short
123456789

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • The easy puzzle is solved by propagation alone (all 81 cells, no guesses).
  • The hard 17-clue puzzle needs search and is solved with 25 guesses.
  • A puzzle with two 5s in row 1 and a 9-cell 'puzzle' are rejected with explanations.

Common errors

RecursionError on hard puzzles

Propagate constraints after each guess so the search depth stays small.

A guess corrupts the board for other branches

Copy the candidate dictionary before each guess (dict(cands)); the sets are replaced, never mutated.

Possible improvements

  • Detect puzzles with more than one solution
  • Rate difficulty by the techniques required
  • Generate new puzzles with a unique solution

Additional challenges

  1. 1Add the naked-pairs technique and measure how many guesses it saves.
  2. 2Solve 16×16 Sudoku.
  3. 3Visualise the search tree depth for the hard puzzle.

Built and tested it yourself? Mark it to update your dashboard.