Algorithms · Visualized
Sudoku Solver
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
A Sudoku solver fills a 9×9 grid so every row, column, and 3×3 box contains digits 1–9 exactly once, using backtracking: try a valid digit in the next empty cell, recurse, and undo the choice if no digit leads to a full solution. Time: O(9^m) worst case — pruned heavily in practice average, O(9^m) worst; space: O(m) — recursion depth.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
Sudoku Solver
BacktrackingA Sudoku solver fills a 9×9 grid so every row, column, and 3×3 box contains digits 1–9 exactly once, using backtracking: try a valid digit in the next empty cell, recurse, and undo the choice if no digit leads to a full solution.
How Sudoku Solver Works
- Find the next empty cell, scanning row by row.
- Try each digit 1–9, checking it does not already appear in the same row, column, or 3×3 box.
- If a digit is valid, place it and recursively attempt to solve the rest of the grid.
- If the recursion succeeds, the puzzle is solved — propagate success upward.
- If it fails (dead end), remove the digit (backtrack) and try the next candidate.
- If no digit works for a cell, return failure to the caller, forcing it to try its next option.
Sudoku Solver Worked Example
Input: A 9×9 grid with a few empty cells (0), e.g. (0,2) missing
Scan to the first empty cell. Try 1 — conflicts with its column; 2 — conflicts with its 3×3 box; ... 6 — row, column, and box are all clear, so place 6 and recurse into the next empty cell. If the remainder solves, 6 was correct; otherwise backtrack and try 7, 8, 9, then reconsider earlier decisions.
def solve_sudoku(board):
def valid(i, j, d):
for k in range(9):
if board[i][k] == d or board[k][j] == d:
return False
br, bc = i // 3 * 3, j // 3 * 3
for x in range(br, br + 3):
for y in range(bc, bc + 3):
if board[x][y] == d:
return False
return True
for i in range(9):
for j in range(9):
if board[i][j] != 0:
continue
for d in range(1, 10):
if valid(i, j, d):
board[i][j] = d
if solve_sudoku(board):
return True
board[i][j] = 0
return False
return TrueBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Sudoku Solver Time & Space Complexity
When to Use Sudoku Solver
- Puzzle-solving apps and puzzle generators.
- The classic teaching example of constraint satisfaction via backtracking.
- A general template for constraint-satisfaction problems (CSPs).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.