🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101

Sudoku solver (backtracking)

Read any Sudoku puzzle and solve it in milliseconds using backtracking, then speed it up with bitmasks.

Intermediate⏱ 5–8 hoursđŸĒœ 7 stepsC++Backtracking

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. 1

    Read the grid

    Load 9 lines of 9 digits into std::array<std::array<int,9>,9>.

  2. 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. 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. 4

    Use bitmasks

    Keep rowMask[9], colMask[9], boxMask[9] as ints; checking a digit becomes (mask >> d) & 1, which is much faster.

  5. 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. 6

    Time it

    Wrap the solve call with std::chrono::high_resolution_clock and print microseconds and the number of recursive calls.

  7. 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