The Wayback Machine - https://web.archive.org/web/20250425190610/https://www.geeksforgeeks.org/the-knights-tour-problem/
Open In App

The Knight’s tour problem

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an n × n chessboard with a Knight starting at the top-left corner (position (0, 0)). The task is to determine a valid Knight’s Tour where where the Knight visits each cell exactly once following the standard L-shaped moves of a Knight in chess.
If a valid tour exists, print an n × n grid where each cell contains the step number (starting from 0) at which the Knight visits that cell. If no tour is possible, print -1.

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: The output represents one valid Knight’s Tour on a 5×5 board. The number in each cell indicates the order in which it is visited starting from (0, 0) as step 0.

Input: n = 3
Output: -1
Explanation: It is not possible to find a valid Knight’s Tour on a 3×3 chessboard since the Knight cannot visit all 9 cells exactly once without revisiting or getting stuck.

[Naive Approach] – Generate All Tours – Theta(8^(n^2)) Time and O(n^2) Space

The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints. 

while there are untried tours
{
generate the next tour
if this tour covers all squares
{
print this path;
}
}

[Using Recursion + Backtracking] – O(8^(n^2)) Time and O(n^2) Space

The idea is to solve the Knight’s Tour problem using recursion and backtracking. The recursive function explores all possible knight moves and backtracks if a move leads to an invalid position.

Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items (Meaning of item varies from problem to problem. In the context of Knight’s tour problem, an item is a Knight’s move). When we add an item, we check if adding the current item violates the problem constraint, if it does then we remove the item and try other alternatives. If none of the alternatives works out then we go to the previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution vector becomes complete then we print the solution.

Steps to implement the above idea:

  • Initialize a 2D board of size n x n filled with -1 to track the knight’s moves.
  • Define two arrays dx and dy representing the 8 possible knight moves in x and y directions.
  • Start from position (0, 0) and set it to 0 to indicate the knight’s first move.
  • Create a recursive function that tries all valid knight moves from the current cell using the isSafe function.
  • If a move leads to a solution, return true, otherwise backtrack by resetting the cell to -1.
  • The base case is when step == n * n, meaning the entire board has been successfully visited.
  • If the recursive function completes successfully, print the filled board, else return -1 to indicate failure.
C++
// C++ Code for Knights Tour Problem
// Using Recursion + Backtracking
#include <bits/stdc++.h>
using namespace std;

// Utility function to check if the 
// move is valid
bool isSafe(int x, int y, int n,
             vector<vector<int>> &board) {
                 
    return (x >= 0 && y >= 0 && x < n 
             && y < n && board[x][y] == -1);
}

// Recursive function to solve Knight's Tour
bool knightsTourUtil(int x, int y, int step, int n,
           vector<vector<int>> &board,
           vector<int> &dx, vector<int> &dy) {
    
    // If all squares are visited
    if (step == n * n) {
        return true;
    }

    // Try all 8 possible knight moves
    for (int i = 0; i < 8; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];

        if (isSafe(nx, ny, n, board)) {
            board[nx][ny] = step;

            if (knightsTourUtil(nx, ny, step + 1, 
                                n, board, dx, dy)) {
                                    
                return true;
            }

            // Backtrack
            board[nx][ny] = -1;
        }
    }

    return false;
}

// Function to start Knight's Tour
vector<vector<int>> knightsTour(int n) {
    
    vector<vector<int>> board(n, vector<int>(n, -1));

    // 8 directions of knight moves
    vector<int> dx = {2, 1, -1, -2, -2, -1, 1, 2};
    vector<int> dy = {1, 2, 2, 1, -1, -2, -2, -1};

    // Start from top-left corner
    board[0][0] = 0;

    if (knightsTourUtil(0, 0, 1, n, board, dx, dy)) {
        return board;
    }

    return { {-1} };
}


// Driver Code
int main() {
    int n = 5;

    vector<vector<int>> res = knightsTour(n);

    for (auto &row : res) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << endl;
    }
    return 0;
}
Java
// Java Code for Knights Tour Problem
// Using Recursion + Backtracking
class GfG {

    static boolean isSafe(int x, int y, int n, int[][] board) {
        return (x >= 0 && y >= 0 && x < n &&
                y < n && board[x][y] == -1);
    }

    static boolean knightsTourUtil(int x, int y, int step, int n,
                                   int[][] board,
                                   int[] dx, int[] dy) {

        // If all squares are visited
        if (step == n * n) {
            return true;
        }

        // Try all 8 possible knight moves
        for (int i = 0; i < 8; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];

            if (isSafe(nx, ny, n, board)) {
                board[nx][ny] = step;

                if (knightsTourUtil(nx, ny, step + 1,
                        n, board, dx, dy)) {

                    return true;
                }

                // Backtrack
                board[nx][ny] = -1;
            }
        }

        return false;
    }

    static int[][] knightsTour(int n) {

        int[][] board = new int[n][n];
        for (int[] row : board) {
            java.util.Arrays.fill(row, -1);
        }

        // 8 directions of knight moves
        int[] dx = {2, 1, -1, -2, -2, -1, 1, 2};
        int[] dy = {1, 2, 2, 1, -1, -2, -2, -1};

        // Start from top-left corner
        board[0][0] = 0;

        if (knightsTourUtil(0, 0, 1, n, board, dx, dy)) {
            return board;
        }

        return new int[][] { {-1} };
    }


    public static void main(String[] args) {
        int n = 5;

        int[][] res = knightsTour(n);

        for (int[] row : res) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python Code for Knights Tour Problem
# Using Recursion + Backtracking

def isSafe(x, y, n, board):
    return x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1

def knightsTourUtil(x, y, step, n, board, dx, dy):
    
    # If all squares are visited
    if step == n * n:
        return True

    # Try all 8 possible knight moves
    for i in range(8):
        nx = x + dx[i]
        ny = y + dy[i]

        if isSafe(nx, ny, n, board):
            board[nx][ny] = step

            if knightsTourUtil(nx, ny, step + 1, n, board, dx, dy):
                return True

            # Backtrack
            board[nx][ny] = -1

    return False

def knightsTour(n):

    board = [[-1 for _ in range(n)] for _ in range(n)]

    # 8 directions of knight moves
    dx = [2, 1, -1, -2, -2, -1, 1, 2]
    dy = [1, 2, 2, 1, -1, -2, -2, -1]

    # Start from top-left corner
    board[0][0] = 0

    if knightsTourUtil(0, 0, 1, n, board, dx, dy):
        return board

    return [[-1]]


if __name__=="__main__":
    n = 5

    res = knightsTour(n)

    for row in res:
        for val in row:
            print(val, end=" ")
        print()
C#
// C# Code for Knights Tour Problem
// Using Recursion + Backtracking
using System;

class GfG {

    static bool isSafe(int x, int y, int n, int[,] board) {
        return (x >= 0 && y >= 0 && x < n &&
                y < n && board[x, y] == -1);
    }

    static bool knightsTourUtil(int x, int y, int step, int n,
                                int[,] board,
                                int[] dx, int[] dy) {

        // If all squares are visited
        if (step == n * n) {
            return true;
        }

        // Try all 8 possible knight moves
        for (int i = 0; i < 8; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];

            if (isSafe(nx, ny, n, board)) {
                board[nx, ny] = step;

                if (knightsTourUtil(nx, ny, step + 1,
                                    n, board, dx, dy)) {

                    return true;
                }

                // Backtrack
                board[nx, ny] = -1;
            }
        }

        return false;
    }

    static int[,] knightsTour(int n) {

        int[,] board = new int[n, n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i, j] = -1;
            }
        }

        // 8 directions of knight moves
        int[] dx = {2, 1, -1, -2, -2, -1, 1, 2};
        int[] dy = {1, 2, 2, 1, -1, -2, -2, -1};

        // Start from top-left corner
        board[0, 0] = 0;

        if (knightsTourUtil(0, 0, 1, n, board, dx, dy)) {
            return board;
        }

        return new int[,] { {-1} };
    }

    static void print2dArray(int[,] arr) {
        int rows = arr.GetLength(0);
        int cols = arr.GetLength(1);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                Console.Write(arr[i, j] + " ");
            }
            Console.WriteLine();
        }
    }

    static void Main() {
        int n = 5;

        int[,] result = knightsTour(n);

        print2dArray(result);
    }
}
JavaScript
// JavaScript Code for Knights Tour Problem
// Using Recursion + Backtracking

function isSafe(x, y, n, board) {
    return x >= 0 && y >= 0 && x < n &&
           y < n && board[x][y] === -1;
}

function knightsTourUtil(x, y, step, n, board, dx, dy) {

    // If all squares are visited
    if (step === n * n) {
        return true;
    }

    // Try all 8 possible knight moves
    for (let i = 0; i < 8; i++) {
        let nx = x + dx[i];
        let ny = y + dy[i];

        if (isSafe(nx, ny, n, board)) {
            board[nx][ny] = step;

            if (knightsTourUtil(nx, ny, step + 1, n, board, dx, dy)) {
                return true;
            }

            // Backtrack
            board[nx][ny] = -1;
        }
    }

    return false;
}

function knightsTour(n) {
    let board = Array.from({ length: n }, () =>
        Array(n).fill(-1)
    );

    // 8 directions of knight moves
    let dx = [2, 1, -1, -2, -2, -1, 1, 2];
    let dy = [1, 2, 2, 1, -1, -2, -2, -1];

    // Start from top-left corner
    board[0][0] = 0;

    if (knightsTourUtil(0, 0, 1, n, board, dx, dy)) {
        return board;
    }

    return [[-1]];
}

// Driver Code
let n = 5;
let res = knightsTour(n);
for (let row of res) {
    console.log(row.join(" "));
}

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 

Time Complexity: O(8^(n^2)), in the worst case due to 8 recursive moves from each of the n^2 cells.
Auxiliary Space: O(n^2), due to board and recursion stack.

Using Warnsdorff’s Algorithm – O(n^3) Time and O(n^2) Space

When solving the Knight’s Tour problem, backtracking isn’t always the most efficient approach. Although it can find a solution, it may explore many wrong paths, leading to a slower solution. For example, if the correct move is the 8th choice, backtracking would try the first 7 incorrect moves before finding the right one.

A better approach is Warnsdorff’s Algorithm, which uses a heuristic to improve performance. The idea behind this algorithm is that, instead of trying all possible moves randomly, we prioritize the moves. In this scenario, we know that the next step is more likely to be in the south or east direction, so prioritizing paths that lead there first is a better strategy.

Refer to this link for detailed explanation and implementation -> Warnsdorff’s Algorithm for Knight’s Tour Problem.

Time Complexity: O(n^3), in practice due to the greedy heuristic, though no strict worst-case bound since it’s probabilistic.
Space Complexity: O(n^2), due to the storage required for the board.



Next Article

Similar Reads