3
这里是我在Python中的代码,拨打knightsTour(0,0,1,sol,xMove,yMove)
应该返回True
,但我得到False
。我无法找到这个错误。使用backtracking在8x8国际象棋棋盘上执行骑士之旅
def safe(x,y,sol):
return x >= 0 and x < 8 and y >= 0 and y < 8 and sol[x][y] == -1
def knightsTour(x,y,move,sol,xMove, yMove):
if move == 8*8 :
return True
#trying all moves from the current coordinate
for k in range(8):
x = x+xMove[k]
y = y+yMove[k]
if safe(x,y,sol):
sol[x][y] = move
if knightsTour(x,y,move+1,sol,xMove,yMove): #calling recursively
return True
else :
sol[x][y] = -1 #backtracking
return False
sol = [[-1 for i in range(8)]for j in range(8)]
sol[0][0] = 0
xMove = [2,1,-1,-2,-2,-1,1,2]
yMove = [1,2,2,1,-1,-2,-2,-1]
print knightsTour(0,0,1,sol,xMove,yMove)
这是一个愚蠢的错误我都做了,谢谢指点出来的人。 但它现在不打印任何既不是真也不是假。 –
@AnujMittal当你包含我的修改时,它会打印出“True”。也许你没有等足够长的时间。计算需要一些时间,在我的机器上一分钟左右。 – timgeb
是的,我现在得到答案,我以前错过了一件事。 –