我的数独解算器完全按照其预期执行 - 除了返回正确的内容。它打印在返回之前应该打印的内容(正确解决的网格),但随后它似乎继续运行一段时间并返回 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)
最佳答案
您在递归中调用 next_cell
,但从未返回其值。
关于python - python 中奇怪的递归行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11486358/