繁体   English   中英

使用回溯在8x8棋盘上实施骑士之旅

[英]Implementing the Knight's Tour on a 8x8 chess board using backtracking

这是我在python中的代码,对knightsTour(0,0,1,sol,xMove,yMove)的调用应返回True但我得到False 我无法追捕这个错误。

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)

那个人花了我一段时间才发现。 错误是你for k in range(8)循环中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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM