You need to enable JavaScript to run this app. Python实现数独回溯算法出现同行同列重复值问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Python实现数独回溯算法出现同行同列重复值问题求助

代码存在的核心问题
  • 参数传递错误:gen_possible_for函数定义要求传入List[List[Cell]]类型的单元格网格,但你调用时传入的是原始输入的List[List[int/None]]类型的数独数组。函数内判断数字是否存在时,是把数字和Cell对象直接比较,永远返回False,导致所有1-9的数字都被判定为合法可选值,完全没有生效行、列、宫的去重规则,这是输出大量重复值、且永远不会触发回溯(decr不打印)的根本原因。
  • 单元格存储结构错误:你生成sudoku_cells列表时用的是x优先的遍历顺序for x in range(9) for y in range(9),且最后将一维列表转回二维网格的索引计算逻辑错误,导致最终输出的数独是旋转后的结果,也会影响坐标匹配。
  • 回溯未清空赋值:回退到上一个单元格时,当前单元格的错误赋值没有重置为None,残留值会干扰后续可选值的计算。
  • 类属性误用:Cell类中times_visited定义为类属性,所有实例共享该值,会导致访问计数混乱,应该放到__init__中定义为实例属性。
修复后的核心代码调整
from math import floor
from typing import List, Optional

class Cell:
    x: int
    y: int
    times_visited: int
    value: Optional[int]
    is_prefilled: bool

    def __init__(self, x: int, y: int, value: Optional[int]):
        self.x = x
        self.y = y
        self.value = value
        self.is_prefilled = value is not None
        self.times_visited = 0 # 实例属性,每个单元格独立计数

def gen_possible_for(cell: Cell, sudoku_cells: List[List[Cell]]) -> List[int]:
    # 提取行已用值
    horizontal = [c.value for c in sudoku_cells[cell.y]]
    # 提取列已用值
    vertical = [sudoku_cells[y][cell.x].value for y in range(9)]
    # 提取3x3宫已用值
    base_x = floor(cell.x / 3) * 3
    base_y = floor(cell.y / 3) * 3
    square = [
        sudoku_cells[base_y + rel_y][base_x + rel_x].value
        for rel_y in range(3)
        for rel_x in range(3)
    ]

    used = set(horizontal + vertical + square)
    return [v for v in range(1, 10) if v not in used]

def solve_sudoku(sudoku: List[List[Optional[int]]]):
    # 先转成二维的Cell数组,方便坐标索引
    sudoku_cells = [[Cell(x, y, sudoku[y][x]) for x in range(9)] for y in range(9)]
    # 把所有待填充的单元格按行优先顺序拉成一维列表,方便回溯遍历
    fill_order = [sudoku_cells[y][x] for y in range(9) for x in range(9) if not sudoku_cells[y][x].is_prefilled]

    i = 0
    while i < len(fill_order):
        cell = fill_order[i]
        possible_values = gen_possible_for(cell, sudoku_cells)

        if not possible_values or cell.times_visited >= len(possible_values):
            # 回溯逻辑:清空当前单元格值、重置计数,回退到上一个单元格
            cell.value = None
            cell.times_visited = 0
            if i == 0:
                # 数独无解
                return False
            print("decr")
            i -= 1
        else:
            cell.value = possible_values[cell.times_visited]
            cell.times_visited += 1
            i += 1
    
    # 转换回二维数字数组返回
    return [[sudoku_cells[y][x].value for x in range(9)] for y in range(9)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 10:54:05