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))

解决方法

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