【发布时间】:2020-01-08 14:22:58
【问题描述】:
我研究数独求解器已经有一段时间了,我刚刚实现了一个数字是否只有一个空格的检测,但它不起作用。此外,以前的一些代码似乎根本不起作用。
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。
【问题讨论】:
-
也许数独并不像你的算法假设的那么简单。
-
@khelwood 我一直在使用这个数独谜题 (i.guim.co.uk/img/media/d84f759d69cbb820e584cf8b35a8505254e5c584/…) 和一个在线求解器 (sudokuwiki.org/sudoku.htm),如果我的代码卡住了,那么根据数独求解器我的代码。
标签: python python-3.x sudoku