数独解算器不能解决所有的数独难题

2024-05-29 02:02:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在一个数独解算器上工作了一段时间了,我刚刚实现了一个数字是否只能进入一个空间的检测,但它不起作用。此外,以前的一些代码似乎根本不起作用

def square_solver(board):
    """Remove confirmed values from the possible values in the squares"""
    global possibleBoard
    # Sets up a modulator to multiply by to get the 3x3 grid of one square with the first value being the rows and the second being the column
    blockNum = [0, 0]
    for _ in range(9):
        # A loop that checks the 9 numbers in one of the squares
        for x in range(3):
            for y in range(3):
                if not board[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y] == " ":  # Checks if that square a number
                    # Checks all the empty spots in one of the squares for that number, then removes them
                    for z in range(3):
                        for w in range(3):
                            try:
                                # Removes the number from the possible board
                                possibleBoard[(blockNum[0] * 3) + z][(blockNum[1] * 3) + w].remove(
                                    board[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y])
                            # If it can't do anything, run this
                            except (ValueError, AttributeError):
                                pass
        blockNum = block_num(blockNum)
    return board
counter = [0] * 9
    blockNum = [0, 0]
    for _ in range(9):
        for x in range(3):
            for y in range(3):
                # Checks the possible board and counts how many time a possible number appears
                if type(possibleBoard[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y]) == list:
                    for z in range(len(possibleBoard[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y])):
                        counter[possibleBoard[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y][z] - 1] += 1
        for x in range(len(counter)):
            # Checks to see if there was any times only one number appeared
            if counter[x] == 1:
                for y in range(3):
                    for z in range(3):
                        try:
                            # Finds the solo number, and makes that number definite
                            if (x + 1) in possibleBoard[(blockNum[0] * 3) + y][(blockNum[0] * 3) + z]:
                                board[(blockNum[0] * 3) + y][(blockNum[0] * 3) + z] = x + 1
                        except TypeError:
                            pass
        blockNum = block_num(blockNum)
        # Rests the counter
        counter = [0] * 9

我重写了这两段代码,但这两次都没有解决数独难题。我不知道怎么回事,但我认为这可能与board[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y]部分有关

完整的代码是here


Tags: the代码inboardnumberforifthat
1条回答
网友
1楼 · 发布于 2024-05-29 02:02:59

您有代码段board[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y]。您所有的问题都源于它应该是board[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y]。因为它是用相同的数字来计算行和列,所以它只能按对角线方向进行。改变这些,解决问题

相关问题 更多 >

    热门问题