Below is the code I am using to test backtracking algo to solve knight's tour, and it's not able to solve for odd board sizes. I would really appreciate if someone could point out the error in the code.
The code works fine for boards of even size, but it fails to find a solution for boards of odd sizes.
def get_valid_moves_warnsdorff(moves, x, y, size):
valid_moves = [(valid_move, len(get_valid_moves(moves, x + valid_move[0], y + valid_move[1], size))) for valid_move in get_valid_moves(moves, x, y, size)]
sorted_moves = sorted(valid_moves, key=lambda w: w[1], reverse=False)
return [move[0] for move in sorted_moves]
Your code requires that your tour is closed (that is, is must be possible to move from the last square back to the first square).
Such a tour does not always exist for all board sizes. In particular, for an M x N
board, if both M
and N
are odd, there will be no closed tour.
To relax the requirements of your code so that open tours are accepted, just get rid of these lines:
origin_touchers = get_valid_moves(moves, 0, 0, size)
if (x, y) not in origin_touchers and -1 not in [grid[origin_toucher[0]][origin_toucher[1]] for origin_toucher in origin_touchers]:
return False
If you do want to keep the closed tour requirement, you could simplify that long condition to if not origin_touchers:
. There's no need to check x,y
(since if you're on the last move you'd already have returned True
) nor for -1
on the grid (since get_valid_moves
already ensures that all the coordinates it returns have -1
on the grid).