DFS. , , DFS , O (2 ^ {count}). Python DFS
def extended_knight_tours(width, height, count):
start_x, start_y = -1, -1
def dfs(x, y, moves_left):
if not (0 <= x < width and 0 <= y < height):
return 0
if moves_left == 0:
if (start_x, start_y) == (x, y):
return 1
else:
return 0
knight_moves = [(1, 2), (-1, 2), (1, -2), (-1, -2),
(2, 1), (2, -1), (-2, 1), (-2, -1)]
return sum(dfs(x + dx, y + dy, moves_left - 1)
for dx, dy in knight_moves)
ans = 0
for x in range(width):
for y in range(height):
start_x = x
start_y = y
ans += dfs(x, y, count)
return ans
, , , memoize DFS ( ).
From a game with this function, I noticed that for every odd account, the answer is zero. Thus, most likely a fast algorithm will find the number of paths with the length / 2 (not necessarily the routes) for each initial position. Then the number of paths with a position at the midpoint can be calculated using count / 2 values, but I will leave this as an exercise for the reader :)