我的數獨解算器完全按照它應該做的 - 除了返回正確的東西。它打印什麼它應該在返回之前(一個正確解決的網格),但它似乎保持運行一點,並返回None。我無法弄清楚發生了什麼事。python中的奇怪遞歸行爲
網格是列表的列表。假設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)
什麼'grid'的格式? (出於好奇) – 2012-07-14 18:42:15
包含9個列表的列表,每個列表包含9個從0-9(含)的整數。 – JohnF 2012-07-14 20:17:33