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

The Knight's tour problem

Last Updated : 06 May, 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 5x5 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 3x3 chessboard since the Knight cannot visit all 9 cells exactly once without revisiting or getting stuck.

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

The idea is to generate all possible tours one by one and check whether each tour satisfies the given 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.

We start from an empty solution vector and one by one add a Knight’s move). When we add a move, we check if adding the current move violates the problem constraint, if it does then we remove it and try other alternatives. If none of the alternatives works out then we go to the previous stage and remove the move added in the previous stage. If we reach the initial stage back then we say that no solution exists. If adding a move doesn’t violate constraints then we recursively add moves one by one. If the solution vector becomes complete then we print the solution.

Step by Step Implementation:

  • 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 knightTourUtil(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 (knightTourUtil(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>> knightTour(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 (knightTourUtil(0, 0, 1, n, board, dx, dy)) {
        return board;
    }

    return { {-1} };
}


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

    vector<vector<int>> res = knightTour(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 knightTourUtil(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 (knightTourUtil(nx, ny, step + 1,
                        n, board, dx, dy)) {

                    return true;
                }

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

        return false;
    }

    static int[][] knightTour(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 (knightTourUtil(0, 0, 1, n, board, dx, dy)) {
            return board;
        }

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


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

        int[][] res = knightTour(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 knightTourUtil(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 knightTourUtil(nx, ny, step + 1, n, board, dx, dy):
                return True

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

    return False

def knightTour(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 knightTourUtil(0, 0, 1, n, board, dx, dy):
        return board

    return [[-1]]


if __name__=="__main__":
    n = 5

    res = knightTour(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 knightTourUtil(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 (knightTourUtil(nx, ny, step + 1,
                                    n, board, dx, dy)) {

                    return true;
                }

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

        return false;
    }

    static int[,] knightTour(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 (knightTourUtil(0, 0, 1, n, board, dx, dy)) {
            return board;
        }

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

    static void Main() {
        int n = 5;

        int[,] result = knightTour(n);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Console.Write(result[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}
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 knightTourUtil(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 (knightTourUtil(nx, ny, step + 1, n, board, dx, dy)) {
                return true;
            }

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

    return false;
}

function knightTour(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 (knightTourUtil(0, 0, 1, n, board, dx, dy)) {
        return board;
    }

    return [[-1]];
}

// Driver Code
let n = 5;
let res = knightTour(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.

Illustration

ezg3
C++
// C++ Code for Knight's Tour Problem
// Using Warnsdorff's Heuristic + Recursion + Backtracking
#include <bits/stdc++.h>
using namespace std;

// Count the number of onward moves from position (x, y)
int countOptions(const vector<vector<int>>& board, int x, int y,
                 const vector<pair<int, int>>& dir) {
    int count = 0;
    int n = board.size();

    for (int i = 0; i < 8; ++i) {
        int nx = x + dir[i].first;
        int ny = y + dir[i].second;
        if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx][ny] == -1) {
            ++count;
        }
    }
    return count;
}

// Generate valid knight moves from (x, y), sorted by fewest onward moves
vector<pair<int, int>> getSortedMoves(const vector<vector<int>>& board, 
                                      int x, int y,const vector<pair<int,
                                      int>>& dir) {
    
    // {optionsCount, directionIndex}
    vector<pair<int, int>> moveList; 

    for (int i = 0; i < 8; ++i) {
        int nx = x + dir[i].first;
        int ny = y + dir[i].second;

        if (nx >= 0 && ny >= 0 && nx < board.size() && ny < board.size() &&
            board[nx][ny] == -1) {
            int options = countOptions(board, nx, ny, dir);
            moveList.emplace_back(options, i);
        }
    }
    
    // Warnsdorff's Rule
    sort(moveList.begin(), moveList.end()); 
    return moveList;
}

// Recursive function to solve the Knight's Tour
bool knightTourUtil(int x, int y, int step, int n, 
                     vector<vector<int>>& board,
                     const vector<pair<int, int>>& dir) {
    
    
    if (step == n * n) return true;

    auto moves = getSortedMoves(board, x, y, dir);

    for (const auto& move : moves) {
        int dirIdx = move.second;
        int nx = x + dir[dirIdx].first;
        int ny = y + dir[dirIdx].second;

        board[nx][ny] = step;
        if (knightTourUtil(nx, ny, step + 1, n, board, dir))
            return true;

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

    return false;
}

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

    // Define 8 knight moves (dx, dy)
    vector<pair<int, int>> dir = {
        {2, 1}, {1, 2}, {-1, 2}, {-2, 1},
        {-2, -1}, {-1, -2}, {1, -2}, {2, -1}
    };

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

    if (knightTourUtil(0, 0, 1, n, board, dir)) {
        return board;
    }

    return {{-1}};
}

// Driver Code
int main() {
    int n = 5;
    vector<vector<int>> result = knightTour(n);

    for (const auto& row : result) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << endl;
    }

    return 0;
}
Java
import java.util.*;

public class KnightTour {

    // Count the number of onward valid knight moves from (x, y)
    static int countOptions(List<List<Integer>> board, int x, int y, 
                            int[][] dir) {
        int count = 0;
        int n = board.size();

        // Check all 8 possible dir
        for (int[] d : dir) {
            int nx = x + d[0];
            int ny = y + d[1];

            // If next cell is inside board and unvisited
            if (nx >= 0 && ny >= 0 && nx < n && ny < n &&
                board.get(nx).get(ny) == -1) {
                count++;
            }
        }
        return count;
    }

    // Generate possible knight moves from (x, y), sorted by
    // least onward options
    static List<int[]> getSortedMoves(List<List<Integer>> board, int x, 
                                      int y, int[][] dir) {
        List<int[]> moves = new ArrayList<>();
        int n = board.size();

        for (int i = 0; i < dir.length; i++) {
            int nx = x + dir[i][0];
            int ny = y + dir[i][1];

            if (nx >= 0 && ny >= 0 && nx < n && ny < n && 
                board.get(nx).get(ny) == -1) {
                // Store onward move count and direction index
                moves.add(new int[]{countOptions(board, nx, ny, dir), i});
            }
        }

        // Sort by Warnsdorff's heuristic (fewer onward moves first)
        moves.sort(Comparator.comparingInt(a -> a[0]));
        return moves;
    }

    // Recursive function to explore knight's tour from (x, y)
    static boolean knightTourUtil(int x, int y, int step, int n,
                                    List<List<Integer>> board,  
                                    int[][] dir) {
        if (step == n * n) return true;

        List<int[]> moves = getSortedMoves(board, x, y, dir);
        for (int[] move : moves) {
            int dirIdx = move[1];
            int nx = x + dir[dirIdx][0];
            int ny = y + dir[dirIdx][1];
            
            // Make move
            board.get(nx).set(ny, step);  
            if (knightTourUtil(nx, ny, step + 1, n, board, dir))
                return true;
                
            // Backtrack
            board.get(nx).set(ny, -1); 
        }
        return false;
    }

    // Function to start the knight's tour
    static List<List<Integer>> knightTour(int n) {
        
        // Initialize the board with -1 (unvisited)
        List<List<Integer>> board = new ArrayList<>();
        for (int i = 0; i < n; ++i) {
            List<Integer> row = new ArrayList<>(Collections.nCopies(n, -1));
            board.add(row);
        }

        // Define all 8 possible knight moves
        int[][] dir = {
            {2, 1}, {1, 2}, {-1, 2}, {-2, 1},
            {-2, -1}, {-1, -2}, {1, -2}, {2, -1}
        };

        board.get(0).set(0, 0); // Start from (0, 0)

        // Start solving from step 1
        if (!knightTourUtil(0, 0, 1, n, board, dir)) {
            // Return {-1} if solution doesn't exist
            return Collections.singletonList(Collections.singletonList(-1));
        }

        return board; // Return completed board
    }

    // Driver code
    public static void main(String[] args) {
        int n = 5;
        List<List<Integer>> result = knightTour(n);
        for (List<Integer> row : result) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
Python
def countOptions(grid, x, y, dir):
    """
    Count the number of valid knight moves from position (x, y).This helps 
    apply Warnsdorff's heuristic: prefer moves with fewer onward options.
    """
    count = 0
    n = len(grid)
    for dx, dy in dir:
        nx, ny = x + dx, y + dy
        if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0:
            count += 1
    return count

def getSortedMoves(grid, x, y, dir):
    """
    Generate all valid knight moves from (x, y),and sort them based on the 
    number of onward options available from the new position.
    """
    options = []
    n = len(grid)
    for i, (dx, dy) in enumerate(dir):
        nx, ny = x + dx, y + dy
        if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0:
            # Store the count of further moves and the move index
            options.append((countOptions(grid, nx, ny, dir), i))
    
    # Sort moves with least onward options first (Warnsdorff's rule)
    options.sort()
    return options

def knightTourUtil(n, x, y, grid, step, dir):
    """
    Recursively try to complete the Knight's Tour from current position 
    (x, y). If all squares are visited (step == n*n), return True.
    Uses backtracking if a path fails.
    """
    if step == n * n:
        return True

    # Get next possible moves from current position
    for _, idx in getSortedMoves(grid, x, y, dir):
        nx = x + dir[idx][0]
        ny = y + dir[idx][1]

        # Mark the next move with the current step
        grid[nx][ny] = step

        # Recursively proceed from the new position
        if knightTourUtil(n, nx, ny, grid, step + 1, dir):
            return True

        # Backtrack: unmark the move
        grid[nx][ny] = 0

    # No valid move found from this position
    return False

def knightTour(n):
    """
    Initializes the chessboard and starts the Knight's Tour from position 
    (0, 0) Returns the completed board or [[-1]] if no solution exists.
    """
    # Create an n x n board initialized with 0
    grid = [[0] * n for _ in range(n)]

    # Start from top-left corner
    grid[0][0] = -1  # Temporarily mark the start cell

    # Define all 8 possible knight moves (dx, dy)
    dir = [
        (2, 1), (1, 2), (-1, 2), (-2, 1),
        (-2, -1), (-1, -2), (1, -2), (2, -1)
    ]

    # Begin the knight's traversal from (0, 0)
    if not knightTourUtil(n, 0, 0, grid, 1, dir):
        return [[-1]]  # No solution found

    # Set the first move to 0 (as it was marked -1)
    grid[0][0] = 0

    # Validate that only one cell (starting cell) was initially unmarked
    empty = sum(row.count(0) for row in grid)
    return grid if empty == 1 else [[-1]]

# Driver Code
if __name__ == "__main__":
    n = 5  # Size of the chessboard (n x n)
    result = knightTour(n)
    for row in result:
        print(' '.join(map(str, row)))
C#
using System;
using System.Collections.Generic;

class GfG{
    
    // Count the number of onward valid knight moves from (x, y)
    static int countOptions(int[,] board, int x, int y, int[][] dir){
        int count = 0;
        int n = board.GetLength(0);

        // Check all 8 possible dir
        for (int i = 0; i < 8; ++i)
        {
            int nx = x + dir[i][0];
            int ny = y + dir[i][1];

            // If next cell is inside grid and unvisited (represented by 0)
            if (nx >= 0 && ny >= 0 && nx < n && ny < n
                && board[nx, ny] == 0)
                ++count;
        }
        return count;
    }

    // Generate possible knight moves from (x, y), sorted by
    // least onward options
    static List<int[]> getSortedMoves(int[,] board, int x, int y, 
                                      int[][] dir)
    {
        var moves = new List<int[]>();
        int n = board.GetLength(0);

        for (int i = 0; i < 8; ++i)
        {
            int nx = x + dir[i][0];
            int ny = y + dir[i][1];

            // If next cell is inside grid and unvisited
            if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx, ny] == 0)
            {
                // Store onward move count and direction index
                moves.Add(new int[] { countOptions(board, nx, ny, dir),
                          i });
            }
        }

        // Sort by Warnsdorff's heuristic (fewer onward moves first)
        moves.Sort((a, b) => a[0].CompareTo(b[0]));
        return moves;
    }

    // Recursive function to explore knight's tour from (x, y)
    static bool knightTourUtil(int x, int y, int step, int n, int[,] board,
                                int[][] dir){
                                    
        if (step == n * n) return true;

        List<int[]> moves = getSortedMoves(board, x, y, dir);
        foreach (var move in moves){
            
            int dirIdx = move[1];
            int nx = x + dir[dirIdx][0];
            int ny = y + dir[dirIdx][1];

            // Make move
            board[nx, ny] = step;

            // Recursively try next move
            if (knightTourUtil(nx, ny, step + 1, n, board, dir))
                return true;

            // Backtrack
            board[nx, ny] = 0;
        }
        return false;
    }

    // Function to start the knight's tour
    static int[,] knightTour(int n){
        
        int[,] board = new int[n, n];
        board[0, 0] = -1;

        // Define all 8 possible knight moves
        int[][] dir = new int[][]{
            new int[]{ -2, -1 }, new int[]{ -1, -2 }, new int[]{ 1, -2 },
            new int[]{ 2, -1 }, new int[]{ 2, 1 }, new int[]{ 1, 2 }, 
            new int[]{ -1, 2 }, new int[]{ -2, 1 }
        };

        // Start solving from step 1
        if (!knightTourUtil(0, 0, 1, n, board, dir)){
            
            // Return {-1} if solution doesn't exist
            return new int[,] { { -1 } };
        }

        // Mark the start position as 0
        board[0, 0] = 0;

        // Check if there's exactly one unvisited cell left
        // (if empty cell count is 1)
        int empty = 0;
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < n; ++j)
                if (board[i, j] == 0) empty++;

        if (empty == 1) return board;

        // If there are more than one empty cells, return {-1}
        // (no valid tour)
        return new int[,] { { -1 } };
    }

    // Driver code
    static void Main(){
        
        int n = 5;
        int[,] res = knightTour(n);

        int rows = res.GetLength(0);
        int cols = res.GetLength(1);

        // Print the result board
        for (int i = 0; i < rows; ++i)
        {
            for (int j = 0; j < cols; ++j)
            {
                Console.Write(res[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
function countOptions(board, x, y, dir) {
  let count = 0;
  let n = board.length;

  // Check all 8 possible dir
  for (let d of dir) {
      let nx = x + d[0];
      let ny = y + d[1];

      // If next cell is inside board and unvisited
      if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx][ny] === -1) {
          count++;
      }
  }
  return count;
}

function getSortedMoves(board, x, y, dir) {
  let moves = [];
  let n = board.length;

  for (let i = 0; i < dir.length; i++) {
      let nx = x + dir[i][0];
      let ny = y + dir[i][1];

      if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx][ny] === -1) {
          // Store onward move count and direction index
          moves.push([countOptions(board, nx, ny, dir), i]);
      }
  }

  // Sort by Warnsdorff's heuristic (fewer onward moves first)
  moves.sort((a, b) => a[0] - b[0]);
  return moves;
}

function knightTourUtil(x, y, step, n, board, dir) {
  if (step === n * n) return true;

  let moves = getSortedMoves(board, x, y, dir);
  for (let move of moves) {
      let dirIdx = move[1];
      let nx = x + dir[dirIdx][0];
      let ny = y + dir[dirIdx][1];

      // Make move
      board[nx][ny] = step;

      // Recursively try next move
      if (knightTourUtil(nx, ny, step + 1, n, board, dir)) {
          return true;
      }

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

function knightTour(n) {
  // Initialize the board with -1 (unvisited)
  let board = Array.from({ length: n }, () => Array(n).fill(-1));

  // Define all 8 possible knight moves
  const dir = [
      [2, 1], [1, 2], [-1, 2], [-2, 1],
      [-2, -1], [-1, -2], [1, -2], [2, -1]
  ];

  board[0][0] = 0; // Start from (0, 0)

  // Start solving from step 1
  if (!knightTourUtil(0, 0, 1, n, board, dir)) {
      // Return [-1] if solution doesn't exist
      return [[-1]];
  }

  return board; // Return completed board
}

// Driver code
let n = 5;
let result = knightTour(n);

// Print the result board
for (let row of result) {
  console.log(row.join(" "));
}

Output
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 

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