我试过做NQueen算法。
当我打电话给词典" y" in" y.values()"我的python没有回应。 但如果我输入" x" in" x.values()"它的工作。
好像我的" y"我在checker()函数中打印时为NULL。 我的#34; y"应该是:
{0: 0}
{0: 0, 1: 2}
{0: 0, 1: 2, 2: 4}
{0: 0, 1: 2, 2: 4, 3: 1}
{0: 0, 1: 2, 2: 4, 3: 1, 4: 3}
{0: 0, 1: 2, 2: 4, 3: 1, 4: 7}
{0: 0, 1: 2, 2: 4, 3: 6}
{0: 0, 1: 2, 2: 4, 3: 6, 4: 1}
{0: 0, 1: 2, 2: 4, 3: 6, 4: 1, 5: 3}
{0: 0, 1: 2, 2: 4, 3: 6, 4: 1, 5: 3, 6: 5}
{0: 0, 1: 2, 2: 4, 3: 7}
{0: 0, 1: 2, 2: 6}
{0: 0, 1: 4}
{0: 2}
{0: 2, 1: 0}
{0: 2, 1: 4}
这是我的代码:
from math import *
N=8
#row = [0 for i in range(N)]
#row=[]
row={}
x={}
y={}
def checker(r,c):
#print(y)
if c in ( x.values() ):
return False
elif x:
dia=0
while dia < r:
if abs(row[dia] - c) == abs(dia - r):
return False
dia+=1
return True
def nqueen(ir):
if ir>N-1: #(ir>N-1):
print(row)
else:
for col in range(N):
row[ir] = col
if (checker(ir,col)):
x[ir] = col
y = dict( (k, x[k]) for k in (range(ir+1)) )
print(y)
nqueen(ir+1)
nqueen(0)
有没有解决方案?