Algorithms · Visualized
Knight's Tour
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
Move a chess knight across an n×n board so that it lands on every square exactly once. Time: O(8^(n²)) unpruned average, O(8^(n²)) worst; space: O(n²) for the board plus O(n²) recursion depth.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
Knight's Tour
BacktrackingMove a chess knight across an n×n board so that it lands on every square exactly once. The knight must move in its L-shape, so at each step there are up to 8 candidate squares; backtracking tries them one by one, undoes moves that lead to dead ends, and keeps going until a full tour is found.
How Knight's Tour Works
- Place the knight on the starting square (the top-left corner) and mark move number 1.
- From the current square, generate all 8 knight moves that stay on the board and land on an unvisited square.
- Order the candidates by Warnsdorff's heuristic — fewest onward moves first — then try the best one: mark it with the next move number and recurse.
- If a dead end is reached (no candidate squares and squares remain), erase the move number and backtrack to the previous square, trying its next candidate.
- The tour succeeds when the move counter reaches n² — every square carries a unique step number.
Knight's Tour Worked Example
Input: 5
Start at (0,0)=1. Moves go (1,2)=2, (2,4)=3, ... each time picking the first in-bounds unvisited L-jump; whenever the knight is stuck, the board un-sets the last square and the previous square tries its next jump, until all 25 squares hold numbers 1..25.
def knights_tour(n):
board = [[0] * n for _ in range(n)]
dirs = [(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2),(1,-2),(2,-1)]
def dfs(i, j, move):
board[i][j] = move
if move == n * n:
return True
for di, dj in dirs:
ni, nj = i + di, j + dj
if 0 <= ni < n and 0 <= nj < n and board[ni][nj] == 0:
if dfs(ni, nj, move + 1):
return True
board[i][j] = 0 # backtrack
return False
return board if dfs(0, 0, 1) else NoneBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Knight's Tour Time & Space Complexity
When to Use Knight's Tour
- A textbook constraint-satisfaction exercise deeper than N-Queens.
- Warnsdorff's heuristic (always jump to the square with fewest onward moves) builds on this exact search skeleton.
- Route-planning problems with piecewise movement constraints (chess engines, puzzle solvers).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.