微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Knight's Tour 仅适用于一种尺寸的棋盘

如何解决Knight's Tour 仅适用于一种尺寸的棋盘

我正在尝试在 python 中实现骑士之旅查找器。假设骑士必须从左上角开始(这里称为 (0,0)),它会找到一个 4x3 场的解,但不会找到任何其他场的解。

def maneuvrability(position,path,width,height):
    if position[0] < width and position[1] < height and position not in path and position[0] >= 0 and position[1] >= 0:
        return True
    else:
        return False
        
def completedness(path,height):
    if len(path) == (width*height):
        return True
    else:
        return False
    
def possible_jumps(pos):
    return_list = []
    return_list.extend([
        (pos[0]-1,pos[1]-2),(pos[0]+1,(pos[0]+2,pos[1]-1),pos[1]+1),(pos[0]-1,pos[1]+2),(pos[0]-2,pos[1]+1)])
    return return_list
    
def knights_tour(width,height,path=[(0,0)]):
    if completedness(path,height):
        return path
    else:
        elem = path[len(path)-1]
        succs = []
        succs.extend(possible_jumps(elem))
        for x in succs:
            if maneuvrability(x,height):
                return knights_tour(width,[y for y in path + [x]])
    
print(knights_tour(4,3))
print(knights_tour(5,5))

解决方法

您的回溯不正确。在每一步,您只检查下一步是否有效,然后返回该移动是否导致骑士的巡回演出。。相反,您需要修改代码以检查所有有效移动,然后查看是否有任何移动导致了完整的骑士之旅。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。