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

The Knight’s tour problem

Last Updated : 17 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems that are typically solved using the backtracking technique have the following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works incrementally and is an optimization over the Naive solution where all possible configurations are generated and tried.
For example, consider the following Knight’s Tour problem. 

Problem Statement:
Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of chess knight must visit each square exactly once. Print the order of each cell in which they are visited.

Example:

Input : 
N = 8
Output:
0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12

The path followed by Knight to cover all the cells
Following is a chessboard with 8 x 8 cells. Numbers in cells indicate the move number of Knight. 

knight-tour-problem


Let us first discuss the Naive algorithm for this problem and then the Backtracking algorithm.

Naive Algorithm for Knight’s tour 
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;
}
}

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.

Backtracking Algorithm for Knight’s tour 

Following is the Backtracking algorithm for Knight’s tour problem. 

If all squares are visited 
print the solution
Else
a) Add one of the next moves to solution vector and recursively
check if this move leads to a solution. (A Knight can make maximum
eight moves. We choose one of the 8 moves in this step).
b) If the move chosen in the above step doesn't lead to a solution
then remove this move from the solution vector and try other
alternative moves.
c) If none of the alternatives work then return false (Returning false
will remove the previously added item in recursion and if false is
returned by the initial call of recursion then "no solution exists" )

Following are implementations for Knight’s tour problem. It prints one of the possible solutions in 2D matrix form. Basically, the output is a 2D 8*8 matrix with numbers from 0 to 63 and these numbers show steps made by Knight. 
 

C++
// C++ program for Knight Tour problem
#include <bits/stdc++.h>
using namespace std;

#define N 8

int solveKTUtil(int x, int y, int movei, int sol[N][N],
                int xMove[], int yMove[]);

/* A utility function to check if i,j are
valid indexes for N*N chessboard */
int isSafe(int x, int y, int sol[N][N])
{
    return (x >= 0 && x < N && y >= 0 && y < N
            && sol[x][y] == -1);
}

/* A utility function to print
solution matrix sol[N][N] */
void printSolution(int sol[N][N])
{
    for (int x = 0; x < N; x++) {
        for (int y = 0; y < N; y++)
            cout << " " << setw(2) << sol[x][y] << " ";
        cout << endl;
    }
}

/* This function solves the Knight Tour problem using
Backtracking. This function mainly uses solveKTUtil()
to solve the problem. It returns false if no complete
tour is possible, otherwise return true and prints the
tour.
Please note that there may be more than one solutions,
this function prints one of the feasible solutions. */
int solveKT()
{
    int sol[N][N];

    /* Initialization of solution matrix */
    for (int x = 0; x < N; x++)
        for (int y = 0; y < N; y++)
            sol[x][y] = -1;

    /* xMove[] and yMove[] define next move of Knight.
    xMove[] is for next value of x coordinate
    yMove[] is for next value of y coordinate */
    int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
    int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };

    // Since the Knight is initially at the first block
    sol[0][0] = 0;

    /* Start from 0,0 and explore all tours using
    solveKTUtil() */
    if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == 0) {
        cout << "Solution does not exist";
        return 0;
    }
    else
        printSolution(sol);

    return 1;
}

/* A recursive utility function to solve Knight Tour
problem */
int solveKTUtil(int x, int y, int movei, int sol[N][N],
                int xMove[8], int yMove[8])
{
    int k, next_x, next_y;
    if (movei == N * N)
        return 1;

    /* Try all next moves from
    the current coordinate x, y */
    for (k = 0; k < 8; k++) {
        next_x = x + xMove[k];
        next_y = y + yMove[k];
        if (isSafe(next_x, next_y, sol)) {
            sol[next_x][next_y] = movei;
            if (solveKTUtil(next_x, next_y, movei + 1, sol,
                            xMove, yMove)
                == 1)
                return 1;
            else
               
               // backtracking
                sol[next_x][next_y] = -1;
        }
    }
    return 0;
}

// Driver Code
int main()
{
      // Function Call
    solveKT();
    return 0;
}

// This code is contributed by ShubhamCoder
C
// C program for Knight Tour problem
#include <stdio.h>
#define N 8

int solveKTUtil(int x, int y, int movei, int sol[N][N],
                int xMove[], int yMove[]);

/* A utility function to check if i,j are valid indexes
   for N*N chessboard */
int isSafe(int x, int y, int sol[N][N])
{
    return (x >= 0 && x < N && y >= 0 && y < N
            && sol[x][y] == -1);
}

/* A utility function to print solution matrix sol[N][N] */
void printSolution(int sol[N][N])
{
    for (int x = 0; x < N; x++) {
        for (int y = 0; y < N; y++)
            printf(" %2d ", sol[x][y]);
        printf("\n");
    }
}

/* This function solves the Knight Tour problem using
   Backtracking.  This function mainly uses solveKTUtil()
   to solve the problem. It returns false if no complete
   tour is possible, otherwise return true and prints the
   tour.
   Please note that there may be more than one solutions,
   this function prints one of the feasible solutions.  */
int solveKT()
{
    int sol[N][N];

    /* Initialization of solution matrix */
    for (int x = 0; x < N; x++)
        for (int y = 0; y < N; y++)
            sol[x][y] = -1;

    /* xMove[] and yMove[] define next move of Knight.
       xMove[] is for next value of x coordinate
       yMove[] is for next value of y coordinate */
    int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
    int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };

    // Since the Knight is initially at the first block
    sol[0][0] = 0;

    /* Start from 0,0 and explore all tours using
       solveKTUtil() */
    if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == 0) {
        printf("Solution does not exist");
        return 0;
    }
    else
        printSolution(sol);

    return 1;
}

/* A recursive utility function to solve Knight Tour
   problem */
int solveKTUtil(int x, int y, int movei, int sol[N][N],
                int xMove[N], int yMove[N])
{
    int k, next_x, next_y;
    if (movei == N * N)
        return 1;

    /* Try all next moves from the current coordinate x, y
     */
    for (k = 0; k < 8; k++) {
        next_x = x + xMove[k];
        next_y = y + yMove[k];
        if (isSafe(next_x, next_y, sol)) {
            sol[next_x][next_y] = movei;
            if (solveKTUtil(next_x, next_y, movei + 1, sol,
                            xMove, yMove)
                == 1)
                return 1;
            else
                sol[next_x][next_y] = -1; // backtracking
        }
    }

    return 0;
}

/* Driver Code */
int main()
{
  
      // Function Call
    solveKT();
    return 0;
}
Java
// Java program for Knight Tour problem
class KnightTour {
    static int N = 8;

    /* A utility function to check if i,j are
       valid indexes for N*N chessboard */
    static boolean isSafe(int x, int y, int sol[][])
    {
        return (x >= 0 && x < N && y >= 0 && y < N
                && sol[x][y] == -1);
    }

    /* A utility function to print solution
       matrix sol[N][N] */
    static void printSolution(int sol[][])
    {
        for (int x = 0; x < N; x++) {
            for (int y = 0; y < N; y++)
                System.out.print(sol[x][y] + " ");
            System.out.println();
        }
    }

    /* This function solves the Knight Tour problem
       using Backtracking.  This  function mainly
       uses solveKTUtil() to solve the problem. It
       returns false if no complete tour is possible,
       otherwise return true and prints the tour.
       Please note that there may be more than one
       solutions, this function prints one of the
       feasible solutions.  */
    static boolean solveKT()
    {
        int sol[][] = new int[8][8];

        /* Initialization of solution matrix */
        for (int x = 0; x < N; x++)
            for (int y = 0; y < N; y++)
                sol[x][y] = -1;

        /* xMove[] and yMove[] define next move of Knight.
           xMove[] is for next value of x coordinate
           yMove[] is for next value of y coordinate */
        int xMove[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
        int yMove[] = { 1, 2, 2, 1, -1, -2, -2, -1 };

        // Since the Knight is initially at the first block
        sol[0][0] = 0;

        /* Start from 0,0 and explore all tours using
           solveKTUtil() */
        if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) {
            System.out.println("Solution does not exist");
            return false;
        }
        else
            printSolution(sol);

        return true;
    }

    /* A recursive utility function to solve Knight
       Tour problem */
    static boolean solveKTUtil(int x, int y, int movei,
                               int sol[][], int xMove[],
                               int yMove[])
    {
        int k, next_x, next_y;
        if (movei == N * N)
            return true;

        /* Try all next moves from the current coordinate
            x, y */
        for (k = 0; k < 8; k++) {
            next_x = x + xMove[k];
            next_y = y + yMove[k];
            if (isSafe(next_x, next_y, sol)) {
                sol[next_x][next_y] = movei;
                if (solveKTUtil(next_x, next_y, movei + 1,
                                sol, xMove, yMove))
                    return true;
                else
                    sol[next_x][next_y]
                        = -1; // backtracking
            }
        }

        return false;
    }

    /* Driver Code */
    public static void main(String args[])
    {
        // Function Call
        solveKT();
    }
}
// This code is contributed by Abhishek Shankhadhar
Python3
# Python3 program to solve Knight Tour problem using Backtracking

# Chessboard Size
n = 8


def isSafe(x, y, board):
    '''
        A utility function to check if i,j are valid indexes 
        for N*N chessboard
    '''
    if(x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1):
        return True
    return False


def printSolution(n, board):
    '''
        A utility function to print Chessboard matrix
    '''
    for i in range(n):
        for j in range(n):
            print(board[i][j], end=' ')
        print()


def solveKT(n):
    '''
        This function solves the Knight Tour problem using 
        Backtracking. This function mainly uses solveKTUtil() 
        to solve the problem. It returns false if no complete 
        tour is possible, otherwise return true and prints the 
        tour. 
        Please note that there may be more than one solutions, 
        this function prints one of the feasible solutions.
    '''

    # Initialization of Board matrix
    board = [[-1 for i in range(n)]for i in range(n)]

    # move_x and move_y define next move of Knight.
    # move_x is for next value of x coordinate
    # move_y is for next value of y coordinate
    move_x = [2, 1, -1, -2, -2, -1, 1, 2]
    move_y = [1, 2, 2, 1, -1, -2, -2, -1]

    # Since the Knight is initially at the first block
    board[0][0] = 0

    # Step counter for knight's position
    pos = 1

    # Checking if solution exists or not
    if(not solveKTUtil(n, board, 0, 0, move_x, move_y, pos)):
        print("Solution does not exist")
    else:
        printSolution(n, board)


def solveKTUtil(n, board, curr_x, curr_y, move_x, move_y, pos):
    '''
        A recursive utility function to solve Knight Tour 
        problem
    '''

    if(pos == n**2):
        return True

    # Try all next moves from the current coordinate x, y
    for i in range(8):
        new_x = curr_x + move_x[i]
        new_y = curr_y + move_y[i]
        if(isSafe(new_x, new_y, board)):
            board[new_x][new_y] = pos
            if(solveKTUtil(n, board, new_x, new_y, move_x, move_y, pos+1)):
                return True

            # Backtracking
            board[new_x][new_y] = -1
    return False


# Driver Code
if __name__ == "__main__":
    
    # Function Call
    solveKT(n)

# This code is contributed by AAKASH PAL
C#
// C# program for
// Knight Tour problem
using System;

class GFG {
    static int N = 8;

    /* A utility function to
    check if i,j are valid
    indexes for N*N chessboard */
    static bool isSafe(int x, int y, int[, ] sol)
    {
        return (x >= 0 && x < N && y >= 0 && y < N
                && sol[x, y] == -1);
    }

    /* A utility function to
    print solution matrix sol[N][N] */
    static void printSolution(int[, ] sol)
    {
        for (int x = 0; x < N; x++) {
            for (int y = 0; y < N; y++)
                Console.Write(sol[x, y] + " ");
            Console.WriteLine();
        }
    }

    /* This function solves the
    Knight Tour problem using
    Backtracking. This function
    mainly uses solveKTUtil() to
    solve the problem. It returns
    false if no complete tour is
    possible, otherwise return true
    and prints the tour. Please note
    that there may be more than one
    solutions, this function prints
    one of the feasible solutions. */
    static bool solveKT()
    {
        int[, ] sol = new int[8, 8];

        /* Initialization of
        solution matrix */
        for (int x = 0; x < N; x++)
            for (int y = 0; y < N; y++)
                sol[x, y] = -1;

        /* xMove[] and yMove[] define
           next move of Knight.
           xMove[] is for next
           value of x coordinate
           yMove[] is for next
           value of y coordinate */
        int[] xMove = { 2, 1, -1, -2, -2, -1, 1, 2 };
        int[] yMove = { 1, 2, 2, 1, -1, -2, -2, -1 };

        // Since the Knight is
        // initially at the first block
        sol[0, 0] = 0;

        /* Start from 0,0 and explore
        all tours using solveKTUtil() */
        if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) {
            Console.WriteLine("Solution does "
                              + "not exist");
            return false;
        }
        else
            printSolution(sol);

        return true;
    }

    /* A recursive utility function
    to solve Knight Tour problem */
    static bool solveKTUtil(int x, int y, int movei,
                            int[, ] sol, int[] xMove,
                            int[] yMove)
    {
        int k, next_x, next_y;
        if (movei == N * N)
            return true;

        /* Try all next moves from
        the current coordinate x, y */
        for (k = 0; k < 8; k++) {
            next_x = x + xMove[k];
            next_y = y + yMove[k];
            if (isSafe(next_x, next_y, sol)) {
                sol[next_x, next_y] = movei;
                if (solveKTUtil(next_x, next_y, movei + 1,
                                sol, xMove, yMove))
                    return true;
                else
                    // backtracking
                    sol[next_x, next_y] = -1;
            }
        }

        return false;
    }

    // Driver Code
    public static void Main()
    {
        // Function Call
        solveKT();
    }
}

// This code is contributed by mits.
JavaScript
<script>

// Javascript program for Knight Tour problem
let N = 8;

// A utility function to check if i,j are
// valid indexes for N*N chessboard 
function isSafe(x, y, sol)
{
    return(x >= 0 && x < N && y >= 0 && 
            y < N && sol[x][y] == -1);
}

// A utility function to print solution
// matrix sol[N][N] 
function printSolution(sol)
{
    for(let x = 0; x < N; x++) 
    {
        for(let y = 0; y < N; y++)
            document.write(sol[x][y] + " ");
            
        document.write("<br/>");
    }
}

// This function solves the Knight Tour problem
// using Backtracking.  This  function mainly
// uses solveKTUtil() to solve the problem. It
// returns false if no complete tour is possible,
// otherwise return true and prints the tour.
// Please note that there may be more than one
// solutions, this function prints one of the
// feasible solutions.  
function solveKT()
{
    let sol = new Array(N);
    for(var i = 0; i < sol.length; i++)
    {
        sol[i] = new Array(N);
    }

    // Initialization of solution matrix 
    for(let x = 0; x < N; x++)
        for(let y = 0; y < N; y++)
            sol[x][y] = -1;

    // xMove[] and yMove[] define next move of Knight.
    // xMove[] is for next value of x coordinate
    // yMove[] is for next value of y coordinate 
    let xMove = [ 2, 1, -1, -2, -2, -1, 1, 2 ];
    let yMove = [ 1, 2, 2, 1, -1, -2, -2, -1 ];

    // Since the Knight is initially at the first block
    sol[0][0] = 0;

    // Start from 0,0 and explore all tours using
    // solveKTUtil() 
    if (!solveKTUtil(0, 0, 1, sol, xMove, yMove))
    {
        document.write("Solution does not exist");
        return false;
    }
    else
        printSolution(sol);

    return true;
}

// A recursive utility function to solve Knight
// Tour problem 
function solveKTUtil(x, y, movei, sol, xMove, yMove)
{
    let k, next_x, next_y;
    if (movei == N * N)
        return true;

    // Try all next moves from the 
    // current coordinate x, y 
    for(k = 0; k < 8; k++) 
    {
        next_x = x + xMove[k];
        next_y = y + yMove[k];
        
        if (isSafe(next_x, next_y, sol)) 
        {
            sol[next_x][next_y] = movei;
            if (solveKTUtil(next_x, next_y, movei + 1,
                            sol, xMove, yMove))
                return true;
            else
                sol[next_x][next_y] = -1; // backtracking
        }
    }
    return false;
}

// Driver code

// Function Call
solveKT();

// This code is contributed by target_2

</script>

Output
  0  59  38  33  30  17   8  63 
 37  34  31  60   9  62  29  16 
 58   1  36  39  32  27  18   7 
 35  48  41  26  61  10  15  28 
 42  57   2  49  40  23   6  19 
 47  50  45  54  25  20  11  14 
 56  43  52   3  22  13  24   5 
 51  46  55  44  53   4  21  12 

Time Complexity : 
There are N2 Cells and for each, we have a maximum of 8 possible moves to choose from, so the worst running time is O(8N^2).

Auxiliary Space: O(N2)

Important Note:
No order of the xMove, yMove is wrong, but they will affect the running time of the algorithm drastically. For example, think of the case where the 8th choice of the move is the correct one, and before that our code ran 7 different wrong paths. It’s always a good idea a have a heuristic than to try backtracking randomly. Like, in this case, we know the next step would probably be in the south or east direction, then checking the paths which lead their first is a better strategy.

Note that Backtracking is not the best solution for the Knight’s tour problem. See the below article for other better solutions. The purpose of this post is to explain Backtracking with an example. 
Warnsdorff’s algorithm for Knight’s tour problem


References: 
http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf 
http://www.cis.upenn.edu/~matuszek/cit594-2009/Lectures/35-backtracking.ppt 
http://mathworld.wolfram.com/KnightsTour.html 
http://en.wikipedia.org/wiki/Knight%27s_tour 
 



Previous Article
Next Article

Similar Reads

Warnsdorff's algorithm for Knight’s tour problem
Problem : A knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once. Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight. We have discussed Backtr
15+ min read
Print all Knight's tour possible from a starting point on NxN chessboard
Given a N x N chessboard with a Knight initially standing on the Xth row and Yth column, the task is to print all possible paths such that the knight must visit each square exactly once. Example: Input: N = 5, X = 1, Y = 1Output: 1 6 15 10 21 14 9 20 5 16 19 2 7 22 11 8 13 24 17 4 25 18 3 12 23 1 6 11 18 21 12 17 20 5 10 7 2 15 22 19 16 13 24 9 4 2
15+ min read
Knight's tour for maximum points
Given a starting position in a 2D matrix representing a grid of points, the task is to find the minimum number of steps required for a knight to collect the maximum points, subject to the following conditions: The knight can move only as per the rules of a standard chess knight (i.e. two squares in one direction and one square in a perpendicular di
15+ min read
Euler Tour of Tree
A Tree is a generalization of connected graph where it has N nodes that will have exactly N-1 edges, i.e one edge between every pair of vertices. Find the Euler tour of tree represented by adjacency list. Examples: Input : Output : 1 2 3 2 4 2 1 Input : Output : 1 5 4 2 4 3 4 5 1 Euler tour is defined as a way of traversing tree such that each vert
6 min read
Euler tour of Binary Tree
Given a binary tree where each node can have at most two child nodes, the task is to find the Euler tour of the binary tree. Euler tour is represented by a pointer to the topmost node in the tree. If the tree is empty, then value of root is NULL. Examples: Input : Output: 1 5 4 2 4 3 4 5 1 Approach: First, start with root node 1, Euler[0]=1 Go to l
7 min read
Total nodes traversed in Euler Tour Tree
Euler tour of tree has been already discussed which flattens the hierarchical structure of tree into array which contains exactly 2*N-1 values. In this post, the task is to prove that the degree of Euler Tour Tree is 2 times the number of nodes minus one. Here degree means the total number of nodes get traversed in Euler Tour. Examples: Input: Outp
7 min read
Sudo Placement | Placement Tour
Given an array A of N positive integers and a budget B. Your task is to decide the maximum number of elements to be picked from the array such that the cumulative cost of all picked elements is less than or equal to budget B. Cost of picking the ith element is given by : A[i] + (i * K) where, K is a constant whose value is equal to the number of el
10 min read
Minimum steps to come back to starting point in a circular tour
Consider circular track with n points marked as 1, 2, ...n. A person is initially placed on point k. The person moves m > 0, slot forward (in circular way) in each step. Find the minimum number of steps required so that the person reaches initial point k. Examples: Input : n = 9, k = 2, m = 6 Output : 3 Explanation : Sequence of moves is 2 =>
7 min read
Find the first circular tour that visits all petrol pumps
Given information about N petrol pumps (say arr[]) that are present in a circular path. The information consists of the distance of the next petrol pump from the current one (in arr[i][1]) and the amount of petrol stored in that petrol pump (in arr[i][0]). Consider a truck with infinite capacity that consumes 1 unit of petrol to travel 1 unit dista
15+ min read
Minimum steps to reach target by a Knight | Set 2
Given a square chessboard of N x N size, the position of Knight and position of a target is given, the task is to find out the minimum steps a Knight will take to reach the target position. Examples : Input : (2, 4) - knight's position, (6, 4) - target cell Output : 2 Input : (4, 5) (1, 1) Output : 3 A BFS approach to solve the above problem has al
15+ min read
Count all possible position that can be reached by Modified Knight
Given a chessboard of size 8 x 8 and the current position of Mirandote. All the rules of this chess game are the same but the knight is modified. We call the new knight "Mirandote". The move of Mirandote is given by a blue color where its current position is denoted by red color in the following image : The task is to find how many possible positio
12 min read
Number of blocks in a chessboard a knight can move to in exactly k moves
Given integers i, j, k and n where (i, j) is the initial position of the Knight on a n * n chessboard, the task is to find the number of positions the Knight can move to in exactly k moves.Examples: Input: i = 5, j = 5, k = 1, n = 10 Output: 8Input: i = 0, j = 0, k = 2, n = 10 Output: 10 The knight can see total 10 different positions in 2nd move.
8 min read
Count all possible visited cells of a knight after N moves
Given the current position of a Knight as (i, j), find the count of different possible positions visited by a knight after N moves (in a 10 x 10 board). Examples: Input: i = 3, j = 3, n = 1 Output: 9 The Knight is initially at position [3][3]. After one move it can visit 8 more cells Input: i = 3, j = 3, n = 2 Output: 35 Approach: The idea is simpl
8 min read
Count of all possible ways to reach a target by a Knight
Given two integers N, M denoting N×M chessboard, the task is to count the number of ways a knight can reach (N, M) starting from (0, 0). Since the answer can be very large, print the answer modulo 109+7. Example: Input: N =3, M= 3Output: 2Explanation: Two ways to reach (3, 3) form (0, 0) are as follows:(0, 0) ? (1, 2) ? (3, 3)(0, 0) ? (2, 1) ? (3,
10 min read
All possible points where knight can reach in one move
Given an integer N and knight position {x, y}, the task is to print all possible sets of points that the knight can reach in one move on an N*N chessboard. Note: Output the points in sorted order. Examples: Input: N = 4, x = 2, y = 2Output:(0, 1)(0, 3)(1, 0)(3, 0)Explanation: Knight can be moved from (2, 2) to (0, 1), (0, 3), (1, 0) and (3, 0). Inp
7 min read
Probability of Knight to remain in the chessboard
Given an NxN chessboard and a Knight at position (x,y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. What is the probability that the Knight remains in the chessboard after taking K steps, with the condition that it can't enter the board again once it leaves it?Examples: Let's ta
12 min read
Possible moves of knight
Given a chess board of dimension m * n. Find number of possible moves where knight can be moved on a chessboard from given position. If mat[i][j] = 1 then the block is filled by something else, otherwise empty. Assume that board consist of all pieces of same color, i.e., there are no blocks being attacked. Examples: Input : mat[][] = {{1, 0, 1, 0},
7 min read
Count of distinct Numbers that can be formed by chess knight in N moves on a mobile keypad
Given an integer N and a chess knight placed in mobile keypad. The task is to count the total distinct N digit numbers which can be formed by the chess knight with N moves. As the answer can be very large give the value of answer modulo 109 + 7. Note: In each move a chess knight can move 2 units horizontally and one unit vertically or two units ver
15+ min read
Minimum steps to reach target by a Knight | Set 1
Given a square chessboard of N x N size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position. Examples:  Input:  knightPosition: (1, 3) , targetPosition: (5, 0) Output: 3Explanation: In above diagram Knight takes 3 step to reach
10 min read
Puzzle | Can a Knight reach bottom from top by visiting all squares
Puzzle Is there a way for a chess knight to start at the top-left corner from a N x N chessboard, visit all the squares of the board exactly once and end at the lower-right corner. Solution We need to traverse all the squares of the chessboard exactly once. Also, the moves of the knight are L-shaped, that is, traverse two squares vertically or hori
2 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
8 queen problem
The eight queens problem is the problem of placing eight queens on an 8×8 chessboard such that none of them attack one another (no two are in the same row, column, or diagonal). More generally, the n queens problem places n queens on an n×n chessboard. There are different solutions for the problem. Backtracking | Set 3 (N Queen Problem) Branch and
8 min read
The Great Tree-List Recursion Problem.
Asked by Varun Bhatia. Question: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The”previous” pointers should be stored in the “small” field and the “next” pointers should be stored in the “large” field. The list sho
1 min read
Custom Tree Problem
You are given a set of links, e.g. a ---> b b ---> c b ---> d a ---> e Print the tree that would form when each pair of these links that has the same character as start and end point is joined together. You have to maintain fidelity w.r.t. the height of nodes, i.e. nodes at height n from root should be printed at same row or column. For
13 min read
Stable Marriage Problem
The Stable Marriage Problem states that given N men and N women, where each person has ranked all members of the opposite sex in order of preference, marry the men and women together such that there are no two people of opposite sex who would both rather have each other than their current partners. If there are no such people, all the marriages are
15+ min read
Approximate solution for Travelling Salesman Problem using MST
We introduced Travelling Salesman Problem and discussed Naive and Dynamic Programming Solutions for the problem in the previous post,. Both of the solutions are infeasible. In fact, there is no polynomial time solution available for this problem as the problem is a known NP-Hard problem. There are approximate algorithms to solve the problem though.
3 min read