The user has asked for Python code to solve a Sudoku puzzle using a backtracking algorithm. It seems straightforward, but I need to focus on clarity while keeping it concise since they didn't request an explanation. I’ll create a main solver function called solve_sudoku(board) that reads a 9x9 grid, possibly represented as a 2D list with 0 for empty spaces. I'll include helper functions like find_empty and is_valid, along with a small example. Let’s get coding!Writing Sudoku code
I’m drafting the code for the Sudoku solution using a backtracking algorithm. I’ll begin with the solve_sudoku(board) function, which looks for empty spots and attempts numbers 1 through 9. If the number is valid, it will recursively call itself; otherwise, it resets the cell to 0.
Next, I’ll define is_valid(board, num, row, col) to check if a number can be placed without violating Sudoku rules. I’ll ensure the indexing logic is clear, labeling block indices consistently for clarity. Let's ensure it all works smoothly!Implementing additional functions
I’m going to implement the find_empty(board) function, which will search the board for empty spots (0s) and return their coordinates. If there are no empty spaces, it will return None.
Next, I’ll set up a __main__ block with a sample puzzle to help demonstrate how the code works. Although parsing strings might be beneficial, it doesn’t seem necessary right now. I'll focus on providing a solid sample puzzle to showcase the Sudoku solver effectively! ```python
"""
Sudoku solver using backtracking.
The board is a 9x9 list of lists of integers.
Empty cells are represented by 0.
"""
def print_board(board):
"""Pretty-print the Sudoku board."""
for i in range(9):
if i % 3 == 0 and i != 0:
print("-" * 21)
row = []
for j in range(9):
if j % 3 == 0 and j != 0:
row.append("|")
row.append(str(board[i][j]) if board[i][j] != 0 else ".")
print(" ".join(row))
def find_empty(board):
"""Find the next empty cell (row, col) or return None if full."""
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return i, j
return None
def is_valid(board, num, row, col):
"""Check if placing num at (row, col) is valid."""
code
# Check row
if any(board[row][j] == num for j in range(9)):
return False
# Check column
if any(board[i][col] == num for i in range(9)):
return False
# Check 3x3 subgrid
box_row_start = (row // 3) * 3
box_col_start = (col // 3) * 3
for i in range(box_row_start, box_row_start + 3):
for j in range(box_col_start, box_col_start + 3):
if board[i][j] == num:
return False
return True
def solve_sudoku(board):
"""Solve the Sudoku puzzle using backtracking. Modifies board in place."""
empty = find_empty(board)
if not empty:
return True # Puzzle solved
code
row, col = empty
for num in range(1, 10):
if is_valid(board, num, row, col):
board[row][col] = num # Tentatively place num
if solve_sudoku(board):
return True
board[row][col] = 0 # Backtrack
return False # Trigger backtracking