我看到了一些数独求解器实现,但我无法弄清楚代码中的问题。我有一个功能sudokusolver成为数独板,必须返回解决的数独板。
def sudokutest(s,i,j,z):
# z is the number
isiValid = np.logical_or((i+1<1),(i+1>9));
isjValid = np.logical_or((j+1<1),(j+1>9));
iszValid = np.logical_or((z<1),(z>9));
if s.shape!=(9,9):
raise(Exception("Sudokumatrix not valid"));
if isiValid:
raise(Exception("i not valid"));
if isjValid:
raise(Exception("j not valid"));
if iszValid:
raise(Exception("z not valid"));
if(s[i,j]!=0):
return False;
for ii in range(0,9):
if(s[ii,j]==z):
return False;
for jj in range(0,9):
if(s[i,jj]==z):
return False;
row = int(i/3) * 3;
col = int(j/3) * 3;
for ii in range(0,3):
for jj in range(0,3):
if(s[ii+row,jj+col]==z):
return False;
return True;
def possibleNums(s , i ,j):
l = [];
ind = 0;
for k in range(1,10):
if sudokutest(s,i,j,k):
l.insert(ind,k);
ind+=1;
return l;
def sudokusolver(S):
zeroFound = 0;
for i in range(0,9):
for j in range(0,9):
if(S[i,j]==0):
zeroFound=1;
break;
if(zeroFound==1):
break;
if(zeroFound==0):
return S;
x = possibleNums(S,i,j);
for k in range(len(x)):
S[i,j]=x[k];
sudokusolver(S);
S[i,j] = 0;
return S;
sudokutest和possibleNums是正确的,只有sudokusolver给出一个RecursionError
答案 0 :(得分:0)
最后,我得到了numpy并且正在运行,我不得不手动复制数字(我的问题)。无论如何,一个非常简单的解决方案在你的代码中(我修改了一下以理解矩阵)你必须找到一种正确的方法来阻止数独完全解决的时刻。为了做到这一点,我使用了一些非常难的东西,比如sys.exit()但你可以实现一个额外的检查,并在矩阵完成后移出整个循环。否则,您将使用新的零写在已完成的顶部之上,并且您将一次又一次地运行相同的步骤。
我只做了一个小调试,但是你可以引入额外的打印输出并检查矩阵本身是如何演变的: - )
至少现在正在努力,希望你能投票支持我的“短期”解决方案。 玩得愉快,玩得开心!!
def sudokutest(s,i,j,z):
# z is the number
isiValid = numpy.logical_or((i+1<1),(i+1>9));
isjValid = numpy.logical_or((j+1<1),(j+1>9));
iszValid = numpy.logical_or((z<1),(z>9));
if s.shape!=(9,9):
raise(Exception("Sudokumatrix not valid"));
if isiValid:
raise(Exception("i not valid"));
if isjValid:
raise(Exception("j not valid"));
if iszValid:
raise(Exception("z not valid"));
if(s[i,j]!=0):
return False;
for ii in range(0,9):
if(s[ii,j]==z):
return False;
for jj in range(0,9):
if(s[i,jj]==z):
return False;
row = int(i/3) * 3;
col = int(j/3) * 3;
for ii in range(0,3):
for jj in range(0,3):
if(s[ii+row,jj+col]==z):
return False;
return True;
def possibleNums(s , i ,j):
l = [];
ind = 0;
for k in range(1,10):
if sudokutest(s,i,j,k):
l.insert(ind,k);
ind+=1;
return l;
def sudokusolver(S):
zeroFound = 0;
for i in range(0,9):
for j in range(0,9):
if(S[i,j]==0):
zeroFound=1;
break;
if(zeroFound==1):
break;
if(zeroFound==0):
print("REALLY The end")
z = numpy.zeros(shape=(9,9))
for x in range(0,9):
for y in range(0,9):
z[x,y] = S[x,y]
print(z)
return z
x = possibleNums(S,i,j);
for k in range(len(x)):
S[i,j]=x[k];
sudokusolver(S);
S[i,j] = 0;
if __name__ == "__main__":
import numpy
#s = numpy.zeros(shape=(9,9))
k = numpy.matrix([0,0,0,0,0,9,0,7,8,5,1,0,0,0,0,0,6,9,9,0,8,0,2,5,0,0,0,0,3,2,0,0,0,0,0,0,0,0,9,3,0,0,0,1,0,0,0,0,4,0,0,0,8,0,8,0,0,0,9,0,7,0,0,6,0,1,0,0,0,0,0,0,0,0,0,0,7,0,8,0,1]).reshape(9,9)
print(k)
print('*'*80)
sudokusolver(k)