2015-12-30 154 views
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) 

回答

4

那一個花了我一段時間才發現。錯誤是你在for k in range(8)循環的每次迭代中修改了xy,即使新位置不安全或最終不能成爲成功騎士巡迴演出的起始位置。 xy表示您目前的起始位置,不應該改變!

您的評論

#trying all moves from the current coordinate 

顯示你想要做什麼,但你實際做的就是努力的舉動,如果新位置沒有保存或不作爲一個成功的騎士的起始位置巡視中,嘗試從新位置而不是當前座標(即調用該函數的xy值)的另一個移動。

你的代碼需要一個簡單的解決(注意註釋):

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): 
     new_x = x+xMove[k] # don't modify x! 
     new_y = y+yMove[k] # don't modify y! 

     if safe(new_x,new_y,sol): # call with candidate values 
      sol[new_x][new_y] = move # mark candidate values on board 
      if knightsTour(new_x,new_y,move+1,sol,xMove,yMove): # call with candidate values 
       return True 
      else : 
       sol[new_x][new_y] = -1 # reset candidate values 
    return False 
+0

這是一個愚蠢的錯誤我都做了,謝謝指點出來的人。 但它現在不打印任何既不是真也不是假。 –

+0

@AnujMittal當你包含我的修改時,它會打印出「True」。也許你沒有等足夠長的時間。計算需要一些時間,在我的機器上一分鐘左右。 – timgeb

+0

是的,我現在得到答案,我以前錯過了一件事。 –