python - python 中奇怪的递归行为

标签 python recursion

我的数独解算器完全按照其预期执行 - 除了返回正确的内容。它打印在返回之前应该打印的内容(正确解决的网格),但随后它似乎继续运行一段时间并返回 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/

相关文章:

类实例的 Python 平方根

python - 有没有办法使用 pymysql 将数据帧插入到 mysql 中?

将 C 代码转换为 MIPS 汇编 - 使用递归的组合函数

Java使用递归void函数的结果,将每个结果添加到列表中并在另一个函数中返回

python - 相同的语句不同的位置导致不同的结果 : local variable "os" referenced before assignment

python - 附加到递归函数中的列表

python - Databricks 连接测试在 "The system cannot find the path specified."上无限期挂起

python - 分类报告 - 精度和 F 分数定义不明确

c++ - 响应 EN_UPDATE 消息时避免递归

python - 计算/减去两个日期时间列之间的差异