简体   繁体   中英

Knight's Tour only solvable for one size board

I am trying to implement a knight's tour finder in python. Assuming the knight must start at the top left corner (called (0,0) here), it finds a solution for a 4x3 field, but not for any other fields.

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,width,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[1]-2),
        (pos[0]+2,pos[1]-1),
        (pos[0]+2,pos[1]+1),
        (pos[0]-1,pos[1]+2),
        (pos[0]+1,pos[1]+2),
        (pos[0]-2,pos[1]-1),
        (pos[0]-2,pos[1]+1)])
    return return_list
    
def knights_tour(width,height,path=[(0,0)]):
    if completedness(path,width,height):
        return path
    else:
        elem = path[len(path)-1]
        succs = []
        succs.extend(possible_jumps(elem))
        for x in succs:
            if maneuvrability(x,path,width,height):
                return knights_tour(width,height,[y for y in path + [x]])
    
print(knights_tour(4,3))
print(knights_tour(5,5))

Your backtracking is not correct. At every step, you are only checking if the next move is valid, and then returning whether or not that move results in a knight's tour. Instead, you need to adapt the code to check all valid moves , and then see if any of them resulted in a complete knight's tour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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