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
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
Complete source code
main.py
What each file does
- main.py
- Units and peers, the propagation functions, the backtracking search, input parsing and output.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
# 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.txtand compare withtests/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
- 1Add the naked-pairs technique and measure how many guesses it saves.
- 2Solve 16×16 Sudoku.
- 3Visualise the search tree depth for the hard puzzle.
Built and tested it yourself? Mark it to update your dashboard.