You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编写的数独求解器持续输出错误解,运行到输出板第二行停止,求错因

数独求解器问题排查与修复

核心错误点

你代码的问题出在回溯逻辑的语法错误:

  • 在solve函数的循环中,当尝试的数值无法得到正确解时,你使用了==(相等判断运算符)而非=(赋值运算符)重置当前空位为0:
    错误代码行:board[row][col] == 0
    修正为:board[row][col] = 0
    该错误会导致错误尝试的数值始终留在数独板上,后续所有的值校验和递归逻辑都会被干扰,所以走到第二行找不到合法值就直接返回False停止运行。

修正后的solve函数代码

def solve(board):
    if not find_zero(board):
        return True
    else:
        row, col = find_zero(board)
    for value in range(1, 10):
        if is_valid(board, row, col, value):
            board[row][col] = value
            if solve(board):
                return True
        # 修正此处运算符
        board[row][col] = 0
    return False

可选优化点

你可以调整find_zero的调用逻辑,避免重复扫描数独板,提升运行效率:

def solve(board):
    row, col = find_zero(board)
    # 没有空位直接返回True
    if row is None:
        return True
    for value in range(1, 10):
        if is_valid(board, row, col, value):
            board[row][col] = value
            if solve(board):
                return True
        board[row][col] = 0
    return False

验证效果

修正后运行你提供的测试数独板,会返回True,数独板会被完整填充为合法解。

内容的提问来源于stack exchange,提问作者swtcoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:39:03