def print_board(board):
"""
Print the Sudoku board.
"""
for i in range(len(board)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - ")
for j in range(len(board[0])):
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(board[i][j])
else:
print(str(board[i][j]) + " ", end="")
def find_empty(board):
"""
Find an empty cell in the Sudoku board.
"""
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j) # row, column
return None
def is_valid(board, num, row, col):
"""
Check if a number is valid at the given position in the board.
"""
# Check row
for i in range(len(board[0])):
if board[row][i] == num and col != i:
return False
# Check column
for i in range(len(board)):
if board[i][col] == num and row != i:
return False
# Check 3x3 box
box_row = row // 3
box_col = col // 3
for i in range(box_row * 3, box_row * 3 + 3):
for j in range(box_col * 3, box_col * 3 + 3):
if board[i][j] == num and (i, j) != (row, col):
return False
return True
def solve_sudoku(board):
"""
Solve the Sudoku puzzle using backtracking.
"""
empty_cell = find_empty(board)
if not empty_cell:
return True
else:
row, col = empty_cell
for num in range(1, 10):
if is_valid(board, num, row, col):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0 # Backtrack
return False
# Example Sudoku board
board = [
[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],
]
solve_sudoku(board)
print_board(board)