Back to Practice
#0305
Sudoku Solver
HardPython45 min25 XP
Problem
Given a 9x9 Sudoku board where empty cells are ".", return the solved board. The input board has exactly one valid solution. Digits are strings "1" through "9".
Why This Matters
Sudoku Solver is one of the best Python backtracking exercises because it forces you to combine clean board scanning, constraint checking, recursion, and undoing choices.
Function Signature
def solve_sudoku(board):
Examples
Example 1
Inputboard = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
Output[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
Backtracking tries valid digits, and when a choice blocks the board later, it undoes the choice and tries the next digit.
Constraints
- The board is always 9x9.
- Empty cells are represented by ".".
- The board has exactly one valid solution.
- Return a solved board; do not print it.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Classic Sudoku puzzle
Inputstandard 9x9 puzzle
Expected[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
The solver fills every blank while respecting row, column, and 3x3 box constraints.
Almost solved board
Inputone missing cell
Expectedsolved board
With only one blank, the missing value is forced by row, column, and box.
Hidden Test Categories
Puzzle with many blanksPuzzle where the first valid-looking digit later failsAlready solved board