def solve_sudoku(board):
"""
Solves a 9x9 Sudoku puzzle using an efficient backtracking algorithm.
Args:
board (list[list[int]]): 9x9 Sudoku board, where 0 represents empty cells.
Returns:
bool: True if solvable, False otherwise. Board is modified in-place if solved.
The algorithm uses:
- Row-major traversal of cells (0 to 80).
- Precomputed boolean tracking arrays for rows, columns, and 3x3 boxes for O(1) validity checks.
- Backtracking: try numbers 1-9 in empty cells, recurse on success, backtrack on failure.
Time Complexity: O(9^m) in worst case (m=empty cells), but highly efficient in practice (~10^6 operations max).
Space Complexity: O(1) auxiliary (fixed-size tracking arrays).
"""
if not board or len(board) != 9 or any(len(row) != 9 for row in board):
return False
# Tracking arrays: row[i][num], col[j][num], box[k][num] where k = (i//3)*3 + j//3
row = [[False] * 10 for _ in range(9)]
col = [[False] * 10 for _ in range(9)]
box = [[False] * 10 for _ in range(9)]
# Initialize tracking arrays from the board
for i in range(9):
for j in range(9):
num = board[i][j]
if num != 0:
box_idx = (i // 3) * 3 + (j // 3)
if row[i][num] or col[j][num] or box[box_idx][num]:
return False # Invalid input puzzle
row[i][num] = col[j][num] = box[box_idx][num] = True
def backtrack(r, c):
# Base case: reached end of board
if r == 9:
return True
# Move to next cell (row-major order)
nr, nc = r, c + 1
if nc == 9:
nr += 1
nc = 0
# Skip filled cells
if board[r][c] != 0:
return backtrack(nr, nc)
# Try numbers 1-9
box_idx = (r // 3) * 3 + (c // 3)
for num in range(1, 10):
if not row[r][num] and not col[c][num] and not box[box_idx][num]:
# Place the number
board[r][c] = num
row[r][num] = col[c][num] = box[box_idx][num] = True
# Recurse
if backtrack(nr, nc):
return True
# Backtrack
board[r][c] = 0
row[r][num] = col[c][num] = box[box_idx][num] = False
return False
return backtrack(0, 0)
Example Usage
# Example Sudoku puzzle (0 = empty)
puzzle = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
if solve_sudoku(puzzle):
print("Solved:")
for row in puzzle:
print(row)
else:
print("No solution")
Output (solved puzzle):
Solved:
[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]
This implementation is highly efficient for standard 9x9 Sudoku, solving most puzzles in milliseconds. For further optimization (e.g., very hard puzzles), you could add Minimum Remaining Values (MRV) heuristic by selecting the empty cell with fewest possibilities first, but it's rarely needed.