DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

I Built Sudoku — Backtracking Solves AND Generates It

Sudoku is a perfect intro to backtracking — the same algorithm both solves the puzzle AND generates new ones. Here's a fully playable build, solver and generator included.

🧩 Play it: https://dev48v.infy.uk/game/day20-sudoku.html

The one rule

isValid(grid, row, col, n) — can digit n go here? Only if n isn't already in that row, that column, or that 3×3 box. Every feature is built on this check.

The backtracking solver

Find the next empty cell. Try 1–9; for each digit that's valid, place it and recurse. If the recursion dead-ends, undo (backtrack) and try the next digit. It either fills the grid or proves no solution exists. ~20 lines.

Generating a puzzle

  1. Fill an empty grid with a random complete solution (the solver, with shuffled digit order).
  2. Remove cells one by one — but after each removal, check the puzzle still has a unique solution (run the solver, bail if it finds two).

More removed cells = harder. That uniqueness check is what separates a real Sudoku from a frustrating one.

The play layer

Givens vs editable cells, live red conflict highlighting, row/col/box selection glow, Check, Hint, Solve, and win detection.

🔨 Full build (isValid → backtracking solver → generate+dig → conflicts → win) on the page: https://dev48v.infy.uk/game/day20-sudoku.html

Part of GameFromZero. 🌐 https://dev48v.infy.uk

Top comments (0)