The Knight’s tour problem

Pattern: Rat in a maze

hard

Move a knight from the corner so that it visits every square once. Backtrack over the 8 knight moves, and try first the square with the fewest onward moves (Warnsdorff's rule), which almost never needs to back up.

The problem

On an n × n board, find a knight's tour: a sequence of knight moves starting at the top-left corner that visits every square exactly once. Return the board with the move number (0 for the start, up to n² - 1) in each square, or an empty board if no tour exists. Tours exist for n = 1 and every n ≥ 5, not for n = 2, 3, 4.

The link above is a GeeksforGeeks article. The function name knightTour and the "empty board if none" rule are this guide's own. Many tours exist, so the tests check that the returned board is a valid tour rather than one exact board.

Think first

  • From a square, how many knight moves are there?
  • What makes plain backtracking slow here?
  • Which squares are most likely to become dead ends if left for later?

Hints

    Brute force, and why it fails

    Plain backtracking in a fixed move order can take an extremely long time on an 8 × 8 board. Warnsdorff's ordering usually finds a tour with little or no backtracking.

    The key insight

    A square with few exits is easy to strand. Visiting it while it is still reachable keeps the tour alive, and that single heuristic makes the search fast.

    Dry run

    move0

    n = 5. The knight starts at (0, 0), marked 0.

    Step 1 of 4

    The plan

    board = all -1; board[0][0] = 0
    function jump(r, c, move):
        if move == n * n: return true
        next = free knight squares from (r, c), sorted by their onward moves
        for each (nr, nc) in next:
            board[nr][nc] = move
            if jump(nr, nc, move + 1): return true
            board[nr][nc] = -1
        return false
    return board if jump(0, 0, 1) else empty
    

    Complexity

    Time
    O(8^(n²)) worst
    Space
    O(n²)

    The worst case is exponential, but with Warnsdorff's rule the search is close to linear in n² for the sizes here. The board and recursion take O(n²).

    Edge cases

    • n = 1: the start square alone is a tour.
    • n = 2, 3, 4: no tour, so the search must explore and fail.
    • Large boards: the recursion depth is n².
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        private static final int[] DR = {2, 1, -1, -2, -2, -1, 1, 2}, DC = {1, 2, 2, 1, -1, -2, -2, -1};
    
        public int[][] knightTour(int n) {
            int[][] board = new int[n][n];
            for (int[] row : board) Arrays.fill(row, -1);
            board[0][0] = 0;
            return jump(board, 0, 0, 1, n) ? board : new int[0][0];
        }
    
        private boolean jump(int[][] b, int r, int c, int move, int n) {
            if (move == n * n) return true;                 // every square visited
            List<int[]> next = new ArrayList<>();
            for (int k = 0; k < 8; k++) {
                int nr = r + DR[k], nc = c + DC[k];
                if (free(b, nr, nc, n)) next.add(new int[]{nr, nc, onward(b, nr, nc, n)});
            }
            next.sort((x, y) -> Integer.compare(x[2], y[2]));   // Warnsdorff: squares with fewest onward moves first
            for (int[] sq : next) {
                b[sq[0]][sq[1]] = move;
                if (jump(b, sq[0], sq[1], move + 1, n)) return true;
                b[sq[0]][sq[1]] = -1;                       // dead end: undo
            }
            return false;
        }
    
        private boolean free(int[][] b, int r, int c, int n) {
            return r >= 0 && c >= 0 && r < n && c < n && b[r][c] == -1;
        }
    
        private int onward(int[][] b, int r, int c, int n) {
            int count = 0;
            for (int k = 0; k < 8; k++) if (free(b, r + DR[k], c + DC[k], n)) count++;
            return count;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> knightTour(int n) {
            vector<vector<int>> board(n, vector<int>(n, -1));
            board[0][0] = 0;
            if (jump(board, 0, 0, 1, n)) return board;
            return vector<vector<int>>();
        }
    
        bool jump(vector<vector<int>>& b, int r, int c, int move, int n) {
            static const int DR[8] = {2, 1, -1, -2, -2, -1, 1, 2}, DC[8] = {1, 2, 2, 1, -1, -2, -2, -1};
            if (move == n * n) return true;                 // every square visited
            vector<vector<int>> next;
            for (int k = 0; k < 8; k++) {
                int nr = r + DR[k], nc = c + DC[k];
                if (!isFree(b, nr, nc, n)) continue;
                int count = 0;                              // onward moves from that square
                for (int j = 0; j < 8; j++) if (isFree(b, nr + DR[j], nc + DC[j], n)) count++;
                next.push_back({count, nr, nc});
            }
            stable_sort(next.begin(), next.end(), [](const vector<int>& x, const vector<int>& y) { return x[0] < y[0]; });   // Warnsdorff
            for (const vector<int>& sq : next) {
                b[sq[1]][sq[2]] = move;
                if (jump(b, sq[1], sq[2], move + 1, n)) return true;
                b[sq[1]][sq[2]] = -1;                       // dead end: undo
            }
            return false;
        }
    
        bool isFree(vector<vector<int>>& b, int r, int c, int n) {
            return r >= 0 && c >= 0 && r < n && c < n && b[r][c] == -1;
        }
    };

    Python

    class Solution:
        MOVES = [(2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)]
    
        def knightTour(self, n: int) -> list[list[int]]:
            board = [[-1] * n for _ in range(n)]
            board[0][0] = 0
    
            def free(r: int, c: int) -> bool:
                return 0 <= r < n and 0 <= c < n and board[r][c] == -1
    
            def jump(r: int, c: int, move: int) -> bool:
                if move == n * n:
                    return True                     # every square visited
                nxt = []
                for dr, dc in self.MOVES:
                    nr, nc = r + dr, c + dc
                    if free(nr, nc):
                        onward = sum(1 for a, b in self.MOVES if free(nr + a, nc + b))
                        nxt.append((onward, nr, nc))
                nxt.sort(key=lambda t: t[0])        # Warnsdorff: squares with fewest onward moves first
                for _, nr, nc in nxt:
                    board[nr][nc] = move
                    if jump(nr, nc, move + 1):
                        return True
                    board[nr][nc] = -1              # dead end: undo
                return False
    
            return board if jump(0, 0, 1) else []

    Common mistakes

    • Counting onward moves including the square you are on.
    • Forgetting to reset a square when backing up.
    • Expecting one particular tour when many are valid.

    Similar problems