Watch a sudoku solver try a digit in each empty cell, check its row, column and box, and backtrack when it gets stuck. A new puzzle every reset, with code.
About this algorithm
A Sudoku solver fills the blanks of a 9 by 9 grid so that every row, every column and every 3 by 3 box holds the digits 1 to 9 once each. The backtracking version walks the cells in reading order, writes the smallest digit that does not clash, moves on, and erases its last guess whenever it reaches a blank where no digit fits.
Use this solver to learn constraint backtracking on a real puzzle, or when you want a short, correct solver for puzzles of everyday difficulty. It is N-Queens with more rules: each guess must pass three checks instead of one, and the board arrives partly filled. For hard puzzles or solving in bulk, change the order: fill the blank with the fewest legal digits first, or use constraint propagation, or Knuth's dancing links for exact cover. Those visit far fewer boards than the plain cell-by-cell order shown here.
Start at row 1, column 1 and move left to right, wrapping to the next row at the end. A cell that already holds a given digit is skipped.
For each digit, look along its row, down its column and around its 3 by 3 box. If the digit is already there, it clashes; try the next one.
Write the first digit that fits and recurse into the next cell. If the walk passes the last cell, every blank is filled and the puzzle is solved.
If no digit from 1 to 9 fits a blank, return false. The blank before it erases its digit and tries the next larger one. If that blank runs out too, the erasing travels further back.
The page picks one of five puzzles at random on each visit, so yours may differ. Take the one whose top row reads blank, blank, blank, 2, 6, blank, 7, blank, 1, with 45 blanks in all. At row 1, column 1, the digits 1 and 2 are already in the row, and 3 fits, so the solver writes 3. At row 1, column 2 all nine digits clash: 1, 2, 6 and 7 are in the row, 3 has just been written there, and 4, 5, 8 and 9 are in the column. So the solver erases the 3, after only 12 tries, and writes 4 in row 1, column 1 instead. The puzzle finishes after 307 tries and 9 erases, with a top row of 4, 3, 5, 2, 6, 9, 7, 8, 1. The hardest of the five, with 58 blanks, needs about 7.9 million tries.
A board with 45 blanks has 9 to the power 45 ways to fill them blindly, the figure on the closing line of the page. Backtracking never builds most of them: a clash at one cell throws away every board that shares the digits written before it. The order still matters: puzzles of similar size can take hundreds of tries or millions.
Time: with B blanks, each blank can try all 9 digits under every choice made before it, so 9^B is the bound, and each check reads 27 cells; real puzzles prune almost all of it. Space: the board is a fixed 81 cells and the solver makes one call per cell, so the stack is never more than 81 deep; on a bigger n² by n² Sudoku both grow with the number of cells.