Sudoku solver (backtracking)
Read any Sudoku puzzle and solve it in milliseconds using backtracking, then speed it up with bitmasks.
What you'll learn
- âRecursion and backtracking
- â2D vectors and bitmasks
- âMeasuring performance with <chrono>
What you'll build
- âReads a puzzle from a file (0 = empty)
- âValidates the puzzle first
- âSolves and pretty-prints the grid
- âReports time taken and cells tried
Step-by-step guide
- 1
Read the grid
Load 9 lines of 9 digits into std::array<std::array<int,9>,9>.
- 2
Validity check
isSafe(r, c, d): d is not already in row r, column c or the 3Ã3 box starting at (r/3*3, c/3*3).
- 3
Backtrack
Find an empty cell; for d in 1..9 if safe, place it and recurse; if recursion fails set the cell back to 0. If no empty cell remains, solved.
- 4
Use bitmasks
Keep rowMask[9], colMask[9], boxMask[9] as ints; checking a digit becomes (mask >> d) & 1, which is much faster.
- 5
Choose the best cell
Pick the empty cell with the fewest candidates (popcount of the free bits) first; this cuts the search dramatically.
- 6
Time it
Wrap the solve call with std::chrono::high_resolution_clock and print microseconds and the number of recursive calls.
- 7
Test hard puzzles
Try well-known "hardest" puzzles and compare times before and after each optimisation.
đ Make it stand out
- +Generate new puzzles with a unique solution
- +SFML or Qt GUI
- +Solve 16Ã16 grids