I'm focused on the backtracking algorithm for Sudoku. My initial understanding of the goal is clear: to devise Python code for solving Sudoku puzzles. The core concept, depth-first search, is the foundation. Now, I need to elaborate on the constraints for backtracking.
Refining the Algorithm's Logic
\n\n
I'm now zeroing in on the algorithm's structure. I've broken down the helper functions needed: print_board is done, now coding find_empty. Next, I'll need is_valid. The recursive solver will tie them all together. Building the is_valid method will be my next challenge.
Mapping Out the Functions
\n\n
My current thinking is focused on is_valid function details. I'm carefully constructing the logic to check rows, columns, and 3x3 boxes. The 3x3 box check requires calculating the starting indices for the box and then iterating through the cells. After that's done, I'll then integrate the solver's recursive nature.
Formulating the Implementation Plan
\n\n
My current thinking centers on the solve function and its interactions with is_valid and find_empty. I'm outlining the base case, the iterative process of testing numbers 1-9, and the crucial backtracking step, which is key to finding a valid solution. I'm also considering how to structure the return values for successful and unsuccessful recursive calls. Finally, I will focus on integrating everything together in the main function.
Formulating Code Implementation
\n\n
My current thinking now centers on the step-by-step code implementation. I'm focusing on the helper functions first, starting with print_board to visually represent the grid. Next will be find_empty and is_valid. Then, I'll integrate them with the solve function, implementing backtracking logic to find the solution. The overall structure is now taking form.
Here is a complete, well-commented Python script that solves a Sudoku puzzle using the recursive backtracking algorithm.
The Code
python
def print_board(board):
"""
Prints the board in a readable Sudoku 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 space in the board (represented by 0).
Returns: (row, col) or None if fully filled.
"""
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 a number is valid in the current position.
Returns: Boolean
"""
# Check Row
for i in range(len(board[0])):
# Check every element in the row, ignoring the position we just inserted
if board[pos[0]][i] == number and pos[1] != i:
return False
# Check Column
for i in range(len(board)):
# Check every element in the column, ignoring the position we just inserted
if board[i][pos[1] == number] and pos[0] != i:
return False
# Correction for logic logic below:
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.
"""
# 1. Find an empty cell
find = find_empty(board)
# 2. Base Case: If no empty cells are found, the puzzle is solved
if not find:
return True
else:
row, col = find
# 3. Try numbers 1 through 9
for i in range(1, 10):
# 4. Check if the number is valid
if is_valid(board, i, (row, col)):
# 5. If valid, add to board
board[row][col] = i
# 6. Recursively call solve on the new board
if solve(board):
return True
# 7. BACKTRACK: If the recursive call returned False,
# reset this cell to 0 and try the next number in the loop
board[row][col] = 0
# 8. If loop finishes and no number is valid, return False to trigger backtrack
return False
# MAIN EXECUTION
if __name__ == "__main__":
# 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("Original Sudoku Board:")
print_board(example_board)
print("\nSolving...\n")
solve(example_board)
print("Solved Sudoku Board:")
print_board(example_board)
How it works (Step-by-Step)
find_empty: The algorithm looks for the first cell containing a 0. If it doesn't find any zeros, it means the board is full and the puzzle is solved.
Guessing Numbers: Once an empty cell is found, the solve function tries numbers from 1 to 9 one by one.
is_valid: Before placing a number, it checks the three Sudoku rules:
Is the number already in the current row?
Is the number already in the current column?
Is the number already in the specific 3x3 box?
Recursion: If the number is valid, it places the number in the cell and calls the solve function again (calling itself).
Backtracking: If the solve function hits a dead end (it tries 1-9 and none fit), it returns False. The program then goes back to the previous cell, resets it to 0, and tries the next number.