sudoku_solver_recursive.html


001| #!/usr/bin/env python3
002| # -*- coding: utf-8 -*-
003| """
003| Created on Wed Apr 16 21:10:21 2025
003| 
003| @author: susantravis
003| """

004| 
005| max_depth = 0
006| 
007| def get_candidates(grid, row, col):
008|     """
008|     For the given cell (row, col) in the grid, return a set of candidate
008|     numbers that are legal based on the current state of the grid.
008|     """

009|     if grid[row][col] != 0:
010|         return set()  # already filled
011| 
012|     # Start with all digits 1-9 and eliminate those that already appear
013|     candidates = set(range(1, 10))
014| 
015| 
016|     # Remove digits present in the same row
017|     for j in range(9):
018|         candidates.discard(grid[row][j])
019| 
020|     # Remove digits present in the same column
021|     for i in range(9):
022|         candidates.discard(grid[i][col])
023| 
024|     # Remove digits present in the same 3x3 subgrid
025|     start_row, start_col = (row // 3) * 3, (col // 3) * 3
026|     for i in range(start_row, start_row + 3):
027|         for j in range(start_col, start_col + 3):
028|             candidates.discard(grid[i][j])
029| 
030|     return candidates
031| 
032| 
033| def select_next_cell(grid):
034|     """
034|     Select the empty cell with the fewest legal candidates.
034|     Returns(row, col), or None if every cell is filled.
034|     """

035|     min_candidates = 10  # More than maximum possible candidates (1-9)
036|     next_cell = None
037|     for i in range(9):
038|         for j in range(9):
039|             if grid[i][j] == 0:
040|                 candidates = get_candidates(grid, i, j)
041|                 if len(candidates) < min_candidates:
042|                     min_candidates = len(candidates)
043|                     next_cell = (i, j)
044|                 # Early return if only one candidate exists
045|                 if min_candidates == 1:
046|                     return next_cell
047|     return next_cell
048| 
049| 
050| def solve_sudoku(grid,depth=0):
051|     """
051|     Solve the Sudoku puzzle using recursive backtracking.
051|     modified grid in-place, andreturns True if solved,
051|     or False if no solution exists.
051|     """

052|     global max_depth
053|     if depth > max_depth:
054|         max_depth = depth
055| 
056|     # Select the next cell to try based on the MRV heuristic
057|     cell = select_next_cell(grid)
058|     if not cell:
059|         return True  # No empty cells, puzzle solved
060| 
061|     row, col = cell
062|     candidates = get_candidates(grid, row, col)
063| 
064|     if not candidates:
065|         # If no candidates are available, backtrack
066|         return False
067| 
068|     for number in candidates:
069|         grid[row][col] = number  # Try assigning the candidate number
070|         # print(str(depth) + " " + f"Trying {number} at ({row},{col})")
071| 
072|         if solve_sudoku(grid, depth + 1):
073|             return True  # If successful, return True
074|         grid[row][col] = 0  # Reset on failure (backtrack)
075| 
076|     return False  # Trigger backtracking if no candidate leads to a solution
077| 
078| 
079| def print_grid(grid):
080|     """
080|     Utility function to print the Sudoku grid in a formatted way.
080|     """

081|     for i in range(9):
082|         row_str = ""
083|         for j in range(9):
084|             row_str += str(grid[i][j]) + " "
085|             if (j + 1) % 3 == 0 and j < 8:
086|                 row_str += "| "
087|         print(row_str)
088|         if (i + 1) % 3 == 0 and i < 8:
089|             print("-" * 21)
090| 
091| 
092| # Sudoku puzzle (0 represents an empty cell)
093| puzzle = [
094|     [0, 0, 5, 3, 0, 0, 0, 0, 0],
095|     [8, 0, 0, 0, 0, 0, 0, 2, 0],
096|     [0, 7, 0, 0, 1, 0, 5, 0, 0],
097|     [4, 0, 0, 0, 0, 5, 3, 0, 0],
098|     [0, 1, 0, 0, 7, 0, 0, 0, 6],
099|     [0, 0, 3, 2, 0, 0, 0, 8, 0],
100|     [0, 6, 0, 5, 0, 0, 0, 0, 9],
101|     [0, 0, 4, 0, 0, 0, 0, 3, 0],
102|     [0, 0, 0, 0, 0, 9, 7, 0, 0]
103| ]
104| 
105| print("Original puzzle:")
106| print_grid(puzzle)
107| 
108| # for i in range(9):
109| # for j in range(9):
110| # print([i,j],get_candidates(puzzle,i,j))
111| 
112| solve_sudoku(puzzle)
113| print("\nSolved puzzle:")
114| print_grid(puzzle)
115| 
116| print(f"\nMaximum recursion depth reached: {max_depth}")
117|