I have a main class, a second class that handles getting a sudoku grid (2D array), and a third class that solves the puzzle and is supposed to return a completed puzzle. When I run the program, the solve method works fine and prints out the solved puzzle. However, when I call SudokuSolver.get_grid()
from another class, the original, unsolved grid that was passed into SudokuSolver
is being returned. Also, when I tried to return self.grid
from the solve()
method, it always returns [[None]]
.
Here is my solver class:
import numpy as np
class SudokuSolver:
def __init__(self, in_grid):
self.grid = in_grid
def get_grid(self):
return self.grid
def solve(self):
for y in range(9):
for x in range(9):
if self.grid[y][x] == 0:
for n in range(1, 10):
if self.possible(y, x, n):
self.grid[y][x] = n
self.solve()
self.grid[y][x] = 0
return
print('Solved')
print(np.matrix(self.grid))
def possible(self, y, x, n):
for i in range(0, 9):
if self.grid[y][i] == n:
return False
for i in range(0, 9):
if self.grid[i][x] == n:
return False
x0 = (x//3) * 3
y0 = (y//3) * 3
for i in range(0, 3):
for j in range(0, 3):
if self.grid[y0 + i][x0 + j] == n:
return False
return True
Second Class:
solver = SudokuSolver(self.get_grid())
solver.solve()
completed = solver.get_grid()
print('Completed')
print(np.matrix(completed))
Why is SudokuSolver
returning the old grid value that was passed in, and not the completed one printed at the end of the solve()
method?