私の数独ソルバーは、正しいものを返すことを除いて、本来あるべきことを正確に実行します。返される直前に何をすべきか (正しく解決されたグリッド) を出力しますが、その後は少し実行を続けているようで、None を返します。何が起こっているのかわかりません。
グリッドはリストのリストです。check_sudoku は、グリッドが有効 (解決されているかどうか) である場合に True を返し、それ以外の場合は False を返すと仮定します。
def solve_sudoku(grid, row=0, col=0):
"Searches for valid numbers to put in blank cells until puzzle is solved."
# Sanity check
if not check_sudoku(grid):
return None
# Sudoku is solved
if row > 8:
return grid
# not a blank, try next cell
elif grid[row][col] != 0:
next_cell(grid, row, col)
else:
# try every number from 1-9 for current cell until one is valid
for n in range(1, 10):
grid[row][col] = n
if check_sudoku(grid):
next_cell(grid, row, col)
else:
# Sudoku is unsolvable at this point, clear cell and backtrack
grid[row][col] = 0
return
def next_cell(grid, row, col):
"Increments column if column is < 8 otherwise increments row"
return solve_sudoku(grid, row, col+1) if col < 8 else solve_sudoku(grid, row+1, 0)