我试图写一些代码来解决一个简单的9X9数独板在python中。 卡在最后一个功能:解决(板)
我的代码:
def check1D(A):
miss = []
for j in list(range(1,len(A)+1)):
if j in A:
continue
else:
miss.append(j)
return(miss)
def check2D(B):
return(check1D(B.flatten()))
def checkRow(board,x,y):
return(check1D(board[x,:]))
def checkCol(board,x,y):
return(check1D(board[:,y]))
def checkBox(board,x,y):
ymin = (y//3)*3
xmin = (x//3)*3
return(check2D(board[xmin:xmin+3,ymin:ymin+3]))
上面的函数检查1D列表。2D会展平阵列以应用1D检查。行,列使用1D检查查找烛台。框计算出右3X3所需的最小/最大值,以使用2D函数检查缺少的数字
def cand(board,x,y):
list = []
box = checkBox(board,x,y)
row = checkRow(board,x,y)
col = checkCol(board,x,y)
for i in box:
if i in row and i in col:
list.append(i)
if len(list) > 1:
list = [0]
elif not list:
list.append(0)
return(list)
def solve(board):
while board.min() == 0:
row = len(board[0,:])
col = len(board[:,0])
for i in range(row):
for j in range(col):
if board[i][j] == 0:
unique = cand(board,i,j)
board[i][j] = unique[0]
return(board)
我检查了我所有的功能,它们似乎都起作用了。cand(board,x,y)在列表中生成唯一的candadite或零
控制台被用于2D数组的B.flatten()方法卡住了
以下是我试图解决的简单数独9X9:
easy = np.array([
[0,0,0, 3,7,0, 0,5,6],
[5,0,0, 0,1,0, 9,7,0],
[0,6,0, 9,8,0, 3,4,0],
[0,0,7, 0,0,2, 0,8,0],
[0,0,9, 0,3,0, 6,0,0],
[0,5,0, 0,3,0, 6,0,0],
[0,7,5, 0,6,9, 0,2,0],
[0,4,8, 0,2,0, 0,0,5],
[2,9,0, 0,5,8, 0,0,0]
])
感谢您的帮助。想知道我在上一个函数中的循环有什么问题。 谢谢
你的例子单靠这个方法是解决不了的。它陷入了一个无休止的循环中,找不到更多的唯一值
卡住之前的最后一块板是:
根据数独规则,
easy
中定义的数据无效(即同一框/行/列中有多个相同的值,如中间框中的3)此答案的其余部分使用以下公式来补偿:
除了
cand
中的唯一数字复选框外,还可以添加一些复选框,以查看是否只有一个值可以进入该行/列/框:这解决了电路板:
您可能还应该检查
solve
中的循环是否在没有更改任何值的情况下完成,以处理陷入无休止循环的程序相关问题 更多 >
编程相关推荐