The user wants Python code to solve a Sudoku puzzle.
The specified method is backtracking.
Understand the Goal: Create a Python script that takes a 9x9 Sudoku grid (represented as a list of lists or similar) and fills in the empty cells (usually represented by 0s) such that every row, column, and 3x3 subgrid contains the digits 1-9 exactly once. The core logic must be a backtracking algorithm.
Backtracking Algorithm Logic:
Find an empty cell.
Try numbers 1 through 9.
Check if the number is valid in that position (according to Sudoku rules).
If valid, place the number and recursively call the solve function.
If the recursive call returns True, the puzzle is solved; return True.
If the recursive call returns False, reset the cell to empty (backtrack) and try the next number.
If all numbers 1-9 are tried and none work, return False (trigger backtracking in the previous step).
Base case: If no empty cells are found, the puzzle is solved; return True.
Data Structure: A 9x9 2D list is standard. 0 or . represents empty cells. I'll use 0.
Helper Functions Needed:
print_board(board): To visualize the result.
find_empty(board): To locate the next 0. Returns (row, col) or None.
is_valid(board, num, pos): To check constraints.
Drafting the Code (Mental or scratchpad):
Finding empty:
Iterate rows i, inside iterate cols j. If board[i][j] == 0, return (i, j). If loop finishes, return None.
Validation (is_valid):
Input: board, num, pos (row, col).
Check Row: Iterate i 0-8. If board[row][i] == num and i != col, return False.
Check Col: Iterate i 0-8. If board[i][col] == num and i != row, return False.
Check Box: Determine top-left corner of the 3x3 box.
box_x = col // 3, box_y = row // 3.
Iterate i 0-2 and j 0-2.
If board[box_y*3 + i][box_x*3 + j] == num and (box_y*3 + i, box_x*3 + j) != pos, return False.
Return True.
Solving (solve):find = find_empty(board)
if not find: return True (Solved)
else: row, col = find
Loop i from 1 to 9:
if is_valid(board, i, (row, col)):
board[row][col] = i
if solve(board): return True
board[row][col] = 0 (Backtrack)
return False
Refining the Code:
Add comments.
Add an example board to test the code immediately.
Make the output readable.
Constructing the Final Response:
Start with a brief explanation of the backtracking approach.
Provide the complete code block.
Explain the key functions (solve, is_valid, find_empty).
Provide an example usage.
Self-Correction/Review during drafting:
Constraint check: In is_valid, make sure not to compare the number against itself at the current position if the number hasn't been placed yet (though usually is_valid is called before placing, so the cell is 0. However, if is_valid is generic, it should handle checking against the specific position).
Actually, in the standard implementation, we check is_validbefore placing. So the cell at (row, col) is currently 0. Therefore, checking board[row][i] == num is safe because board[row][col] is 0, which is not num.
Wait, looking at the box check logic.
box_x = pos[1] // 3box_y = pos[0] // 3
Loop i in range(3), j in range(3).
Check board[box_y*3 + i][box_x*3 + j].
Since board[pos[0]][pos[1]] is 0, it won't match num. So explicit exclusion of the current cell isn't strictly necessary, but good for robustness if the logic changes.
Let's stick to the simplest logic: check row, check col, check box. Since the cell is 0, it won't cause a false positive collision.
Final Code Structure:
python
def solve(board):
find = find_empty(board)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if is_valid(board, i, (row, col)):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
# ... is_valid ...
# ... find_empty ...
# ... print_board ...
# ... Main execution block ...
This looks solid. I will now generate the response based on these steps.
Here is a clean and efficient Python implementation of a Sudoku solver using the backtracking algorithm.
The Algorithm
Find an empty cell: Scan the grid to find a cell that is currently empty (represented by 0).
Try numbers 1-9: Attempt to place digits 1 through 9 in that empty cell.
Check validity: For each digit, check if it adheres to Sudoku rules (no duplicate in row, column, or 3x3 box).
Recursive Step: If the number is valid, place it and recursively call the function to solve the rest of the board.
Backtrack: If the recursive call returns False (meaning the path led to a dead end), reset the cell to 0 and try the next number. If all numbers fail, return False to trigger backtracking in the previous step.
Python Code
python
def print_board(board):
"""
Helper function to print the board in a readable format.
"""
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):
"""
Finds an empty cell in the board (represented by 0).
Returns: (row, col) tuple or None
"""
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j) # row, col
return None
def is_valid(board, number, pos):
"""
Checks if the number is valid in the current position.
pos: (row, col)
"""
# Check Row
for i in range(len(board[0])):
if board[pos[0]][i] == number and pos[1] != i:
return False
# Check Column
for i in range(len(board)):
if board[i][pos[1]] == number and pos[0] != i:
return False
# Check 3x3 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] == number and (i, j) != pos:
return False
return True
def solve(board):
"""
Solves the sudoku board using backtracking.
Returns: True if solvable, False if not.
"""
find = find_empty(board)
# Base case: If no empty cells are found, the puzzle is solved
if not find:
return True
else:
row, col = find
# Try numbers 1 through 9
for i in range(1, 10):
if is_valid(board, i, (row, col)):
# If valid, assign the number to the board
board[row][col] = i
# Recursively try to solve the rest of the board
if solve(board):
return True
# If the recursive call fails (returns False), backtrack:
# Reset the cell to 0 and try the next number in the loop
board[row][col] = 0
return False
# --- Example Usage ---
# 0 represents an empty cell
example_board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
print("Unsolved Board:")
print_board(example_board)
print("\nSolving...\n")
solve(example_board)
print("Solved Board:")
print_board(example_board)