![]() |
VOOZH | about |
Given an integer n, consider an n × n chessboard. A Knight starts at the top-left corner (0, 0) and must visit every cell exactly once following the Knight’s standard moves in chess (two steps in one direction and one step perpendicular).
Examples:
Input: n = 5
Output:
[[0, 5, 14, 9, 20],
[13, 8, 19, 4, 15],
[18, 1, 6, 21, 10],
[7, 12, 23, 16, 3],
[24, 17, 2, 11, 22]]
Explanation: Each number represents the step at which the Knight visits that cell, starting from (0, 0) as step 0. The output shows one valid Knight’s Tour on a 5×5 board.Input: n = 3
Output: [-1]
Explanation: It is not possible to find a valid Knight's Tour on a 3x3 chessboard since the Knight cannot visit all 9 cells exactly once without revisiting or getting stuck.
Table of Content
We will use recursion and backtracking to build a sequence of knight moves that visits every cell once. Start at (0, 0), mark each visited cell with the move number, and try all 8 knight moves from the current cell. If a move leads to a dead end, undo it (backtrack) and try the next move. Stop when you have placed n*n moves (success) or exhausted all options (failure).
0 5 14 9 20 13 8 19 4 15 18 1 6 21 10 7 12 23 16 3 24 17 2 11 22
When solving the Knight's Tour problem, backtracking works but is inefficient because it explores many unnecessary paths. If the correct move happens to be the last option, the algorithm wastes time trying all the wrong ones first.
A smarter strategy is Warnsdorff’s Algorithm, which uses a heuristic to reduce backtracking. Instead of trying moves in random order, it always chooses the next move with the fewest onward moves (the cell with the smallest degree). This prevents the knight from getting stuck early and greatly improves efficiency.
Illustration
0 21 10 15 6 11 16 7 20 9 24 1 22 5 14 17 12 3 8 19 2 23 18 13 4