Problem: Make the following code snippet into a function in Python3 capable of solving Any Sudoku puzzle
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,
Approach: called Backtracking. This is a brute-force approach that explores all possible paths to a solution.
Key considerations:
- Recursion:
If the number is valid, it is placed in the cell, and the algorithm recursively calls itself to try to fill the next empty cell.
- Success: If the recursive call returns
True, the puzzle is solved, and the solution propagates back up the chain.
- Backtracking: If the recursive call returns
False (meaning we hit a dead end later in the puzzle), the algorithm resets the current cell back to 0
Let me implement this solution.
Here is the step-by-step reasoning and the final Python code to solve the Sudoku puzzle.
Reasoning
To solve a Sudoku puzzle programmatically, we utilize an algorithm called Backtracking. This is a brute-force approach that explores all possible paths to a solution.
- Find an Empty Cell: The algorithm scans the grid to find a cell that contains a
0 (representing an empty spot).
- Try Numbers 1-9: Once an empty cell is found, the algorithm tries to place numbers from 1 through 9 into that cell.
- Check Validity: For every number placed, the algorithm checks if it violates the rules of Sudoku:
- Is the number already in the current row?
- Is the number already in the current column?
- Is the number already in the current 3x3 box?
- Recursion:
- If the number is valid, it is placed in the cell, and the algorithm recursively calls itself to try to fill the next empty cell.
- Success: If the recursive call returns
True, the puzzle is solved, and the solution propagates back up the chain.
- Backtracking: If the recursive call returns
False (meaning we hit a dead end later in the puzzle), the algorithm resets the current cell back to 0 and tries the next number in the sequence (1-9).
- Termination: If the algorithm tries numbers 1-9 for a specific empty cell and none work, it returns
False, signaling to the previous step to backtrack. If no empty cells are left, the puzzle is solved.
Python Code
Here is the complete solution encapsulated in a function solve_sudoku, along with helper functions and the example usage.
def solve_sudoku(bo):
"""
Solves a sudoku board using backtracking.
:param bo: 2D list representing the sudoku board (0 represents empty)
:return: True if solvable, False if not
"""
find = find_empty(bo)
if not find:
return True # No empty spots left, puzzle solved
else:
row, col = find