Sure! Here's an example implementation of a Sudoku solver using recursive backtracking in Python:
def solve_sudoku(board):
"""
Solves the Sudoku puzzle using recursive backtracking.
:param board: A 2D list representing the Sudoku board, where empty cells are represented by 0s.
:return: The solved Sudoku board.
"""
find = find_empty(board)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if valid(board, i, (row, col)):
board[row][col] = i
if solve_sudoku(board):
return True
board[row][col] = 0
return False
def valid(board, num, pos):
"""
Checks if it is valid to place the given number at the specified position in the Sudoku board.
:param board: A 2D list representing the Sudoku board.
:param num: The number to be placed on the board.
:param pos: A tuple representing the row and column of the position where the number is to be placed.
:return: True if it is valid to place the number, False otherwise.
"""
# Check row
for i in range(len(board[0])):
if board[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(len(board)):
if board[i][pos[1]] == num and pos[0] != i:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if board[i][j] == num and (i, j) != pos:
return False
return True
def find_empty(board):
"""
Finds the first empty cell in the Sudoku board.
:param board: A 2D list representing the Sudoku board.
:return: A tuple representing the row and column of the empty cell, or None if the board is full.
"""
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
To use the solver, simply call the solve_sudoku function with a 2D list representing the Sudoku board, where empty cells are represented by 0s. For example:
board = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0]
]
solve_sudoku(board)
print(board)
This will print the following output:
[[3, 1, 6, 5, 7, 8, 4, 9, 2], [5, 2, 9, 1,