sudosol

sudoku solver
Index Commits Files Refs LICENSE
sudoku.py (1932B)
   1 class Sudoku:
   2     def __init__(self, dim):
   3         self.dim = dim  # Dimension of the sudoku
   4         self.sudoku = []
   5 
   6     # Load the sudoku into a 2D-List
   7     def load_from_file(self, filename):
   8         self.sudoku = [[0] * self.dim for i in range(self.dim)]
   9 
  10         with open(filename, "rt") as f:
  11             for line, i in zip(f, range(self.dim)):
  12                 for char, j in zip(line, range(self.dim)):
  13                     if char != '\n':
  14                         self.sudoku[i][j] = int(char)
  15 
  16     # Prints the sudoku in a list format
  17     def print(self):
  18         for x in range(len(self.sudoku)):
  19             print(self.sudoku[x])
  20 
  21     def set_value(self, val, r, c):
  22         self.sudoku[r][c] = val
  23 
  24     def get_value(self, r, c) -> int:
  25         return self.sudoku[r][c]
  26 
  27     def find_empty_cell(self) -> tuple[bool, int, int]:
  28         for r in range(self.dim):
  29             for c in range(self.dim):
  30                 if self.sudoku[r][c] == 0:
  31                     return True, r, c
  32 
  33         return False, 0, 0
  34 
  35     def is_value_valid(self, value, r, c):
  36         if value in self.sudoku[r]:
  37             return False
  38 
  39         col_values = [self.sudoku[i][c] for i in range(self.dim)]
  40 
  41         if value in col_values:
  42             return False
  43 
  44         row_start = (r // 3) * 3
  45         col_start = (c // 3) * 3
  46 
  47         for r in range(row_start, row_start + 3):
  48             for c in range(col_start, col_start + 3):
  49                 if self.sudoku[r][c] == value:
  50                     return False
  51 
  52         return True
  53 
  54 
  55     def solve(self):
  56         find, r, c = self.find_empty_cell()
  57         if find == False:
  58             # Sudoku solved!
  59             return True
  60 
  61         for value in range(1, self.dim + 1):
  62             if self.is_value_valid(value, r, c):
  63                 self.set_value(value, r, c)
  64                 if self.solve():
  65                     return True
  66 
  67             self.set_value(0, r, c)
  68         return False