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

Backtracking

Move 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

  1. Place the knight on the starting square (the top-left corner) and mark move number 1.
  2. From the current square, generate all 8 knight moves that stay on the board and land on an unvisited square.
  3. 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.
  4. 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.
  5. 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.

Knight's TourO(8^(n²))
Move a knight to every square exactly once, backtracking from dead ends.
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
moves0
Step 1 / 27
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Knight's Tour on 5×5: visit every square exactly once with knight moves.
Python · Backtracking in Code
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 None

Behind 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

BestFast in practice with good ordering
AverageO(8^(n²)) unpruned
WorstO(8^(n²))
SpaceO(n²) for the board plus O(n²) recursion depth

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.