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

Python实现的LeetCode数独求解器仅输出部分解,原因是什么?

数独求解器代码问题修复

你的代码仅返回部分解的核心原因是回溯回退步骤存在语法错误,逻辑完全失效:

  • 你在递归返回false(当前路径走不通)时的回退代码写的是board[i][j]==".",这是比较判断语句,不会修改棋盘的值,正确写法应该是赋值语句board[i][j] = "."

因为没有正确回退错误填入的数字,后续的合法性校验会把这些错误值当成已存在的合法值,导致递归提前终止,只能得到部分填充的棋盘。


修复后完整代码

class Solution(object):
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: None Do not return anything, modify board in-place instead.
        """
        def isValid(board, row, col, c):
          nRow = 3*(row//3)
          nCol = 3*(col//3)

          for i in range(9):
            # 检查行
            if board[row][i]==c:
              return False
            # 检查列
            if board[i][col]==c:
              return False
            # 检查3*3宫格
            if board[nRow+(i//3)][nCol+(i%3)]==c:
              return False
          return True


        def solve(board):
          for i in range(len(board)):
            for j in range(len(board)):
              if board[i][j]==".":
                for c in ["1","2","3","4","5","6","7","8","9"]:
                  if isValid(board, i, j, c): 
                    board[i][j]=c
                    if solve(board):
                        return True
                    # 修复回退逻辑,改为赋值操作
                    board[i][j] = "."
                return False
          return True
        solve(board)
        
        
if __name__=='__main__':
  board1 = [["5","3",".",".","7",".",".",".","."],
            ["6",".",".","1","9","5",".",".","."],
            [".","9","8",".",".",".",".","6","."],
            ["8",".",".",".","6",".",".",".","3"],
            ["4",".",".","8",".","3",".",".","1"],
            ["7",".",".",".","2",".",".",".","6"],
            [".","6",".",".",".",".","2","8","."],
            [".",".",".","4","1","9",".",".","5"],
            [".",".",".",".","8",".",".","7","9"]]

  Solution().solveSudoku(board1)
  print(board1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:51:01