The Wayback Machine - https://web.archive.org/web/20240921233419/https://www.geeksforgeeks.org/warnsdorffs-algorithm-knights-tour-problem/
Open In App

Warnsdorff’s algorithm for Knight’s tour problem

Last Updated : 26 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 
 

knight-tour-problem

We have discussed Backtracking Algorithm for solution of Knight’s tour. In this post Warnsdorff’s heuristic is discussed. 
Warnsdorff’s Rule: 

  1. We can start from any initial position of the knight on the board.
  2. We always move to an adjacent, unvisited square with minimal degree (minimum number of unvisited adjacent).

This algorithm may also more generally be applied to any graph. 

Some definitions:  

  • A position Q is accessible from a position P if P can move to Q by a single Knight’s move, and Q has not yet been visited.
  • The accessibility of a position P is the number of positions accessible from P.

Algorithm:  

  1. Set P to be a random initial position on the board
  2. Mark the board at P with the move number “1”
  3. Do following for each move number from 2 to the number of squares on the board: 
    • let S be the set of positions accessible from P.
    • Set P to be the position in S with minimum accessibility
    • Mark the board at P with the current move number
  4. Return the marked board — each square will be marked with the move number on which it is visited.

Below is implementation of above algorithm.  

C++




// C++ program to for Knight's tour problem using
// Warnsdorff's algorithm
#include <bits/stdc++.h>
#define N 8
 
// Move pattern on basis of the change of
// x coordinates and y coordinates respectively
static int cx[N] = {1,1,2,2,-1,-1,-2,-2};
static int cy[N] = {2,-2,1,-1,2,-2,1,-1};
 
// function restricts the knight to remain within
// the 8x8 chessboard
bool limits(int x, int y)
{
    return ((x >= 0 && y >= 0) && (x < N && y < N));
}
 
/* Checks whether a square is valid and empty or not */
bool isempty(int a[], int x, int y)
{
    return (limits(x, y)) && (a[y*N+x] < 0);
}
 
/* Returns the number of empty squares adjacent
   to (x, y) */
int getDegree(int a[], int x, int y)
{
    int count = 0;
    for (int i = 0; i < N; ++i)
        if (isempty(a, (x + cx[i]), (y + cy[i])))
            count++;
 
    return count;
}
 
// Picks next point using Warnsdorff's heuristic.
// Returns false if it is not possible to pick
// next point.
bool nextMove(int a[], int *x, int *y)
{
    int min_deg_idx = -1, c, min_deg = (N+1), nx, ny;
 
    // Try all N adjacent of (*x, *y) starting
    // from a random adjacent. Find the adjacent
    // with minimum degree.
    int start = rand()%N;
    for (int count = 0; count < N; ++count)
    {
        int i = (start + count)%N;
        nx = *x + cx[i];
        ny = *y + cy[i];
        if ((isempty(a, nx, ny)) &&
           (c = getDegree(a, nx, ny)) < min_deg)
        {
            min_deg_idx = i;
            min_deg = c;
        }
    }
 
    // IF we could not find a next cell
    if (min_deg_idx == -1)
        return false;
 
    // Store coordinates of next point
    nx = *x + cx[min_deg_idx];
    ny = *y + cy[min_deg_idx];
 
    // Mark next move
    a[ny*N + nx] = a[(*y)*N + (*x)]+1;
 
    // Update next point
    *x = nx;
    *y = ny;
 
    return true;
}
 
/* displays the chessboard with all the
  legal knight's moves */
void print(int a[])
{
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < N; ++j)
            printf("%d\t",a[j*N+i]);
        printf("\n");
    }
}
 
/* checks its neighbouring squares */
/* If the knight ends on a square that is one
   knight's move from the beginning square,
   then tour is closed */
bool neighbour(int x, int y, int xx, int yy)
{
    for (int i = 0; i < N; ++i)
        if (((x+cx[i]) == xx)&&((y + cy[i]) == yy))
            return true;
 
    return false;
}
 
/* Generates the legal moves using warnsdorff's
  heuristics. Returns false if not possible */
bool findClosedTour()
{
    // Filling up the chessboard matrix with -1's
    int a[N*N];
    for (int i = 0; i< N*N; ++i)
        a[i] = -1;
 
    // Random initial position
    int sx = rand()%N;
    int sy = rand()%N;
 
    // Current points are same as initial points
    int x = sx, y = sy;
    a[y*N+x] = 1; // Mark first move.
 
    // Keep picking next points using
    // Warnsdorff's heuristic
    for (int i = 0; i < N*N-1; ++i)
        if (nextMove(a, &x;, &y;) == 0)
            return false;
 
    // Check if tour is closed (Can end
    // at starting point)
    if (!neighbour(x, y, sx, sy))
        return false;
 
    print(a);
    return true;
}
 
// Driver code
int main()
{
    // To make sure that different random
    // initial positions are picked.
    srand(time(NULL));
 
    // While we don't get a solution
    while (!findClosedTour())
    {
    ;
    }
 
    return 0;
}


Java




// Java program to for Knight's tour problem using
// Warnsdorff's algorithm
import java.util.concurrent.ThreadLocalRandom;
 
class GFG
{
    public static final int N = 8;
 
    // Move pattern on basis of the change of
    // x coordinates and y coordinates respectively
    public static final int cx[] = {1, 1, 2, 2, -1, -1, -2, -2};
    public static final int cy[] = {2, -2, 1, -1, 2, -2, 1, -1};
 
    // function restricts the knight to remain within
    // the 8x8 chessboard
    boolean limits(int x, int y)
    {
        return ((x >= 0 && y >= 0) &&
                 (x < N && y < N));
    }
 
    /* Checks whether a square is valid and
    empty or not */
    boolean isempty(int a[], int x, int y)
    {
        return (limits(x, y)) && (a[y * N + x] < 0);
    }
 
    /* Returns the number of empty squares
    adjacent to (x, y) */
    int getDegree(int a[], int x, int y)
    {
        int count = 0;
        for (int i = 0; i < N; ++i)
            if (isempty(a, (x + cx[i]),
                           (y + cy[i])))
                count++;
 
        return count;
    }
 
    // Picks next point using Warnsdorff's heuristic.
    // Returns false if it is not possible to pick
    // next point.
    Cell nextMove(int a[], Cell cell)
    {
        int min_deg_idx = -1, c,
            min_deg = (N + 1), nx, ny;
 
        // Try all N adjacent of (*x, *y) starting
        // from a random adjacent. Find the adjacent
        // with minimum degree.
        int start = ThreadLocalRandom.current().nextInt(1000) % N;
        for (int count = 0; count < N; ++count)
        {
            int i = (start + count) % N;
            nx = cell.x + cx[i];
            ny = cell.y + cy[i];
            if ((isempty(a, nx, ny)) &&
                (c = getDegree(a, nx, ny)) < min_deg)
            {
                min_deg_idx = i;
                min_deg = c;
            }
        }
 
        // IF we could not find a next cell
        if (min_deg_idx == -1)
            return null;
 
        // Store coordinates of next point
        nx = cell.x + cx[min_deg_idx];
        ny = cell.y + cy[min_deg_idx];
 
        // Mark next move
        a[ny * N + nx] = a[(cell.y) * N +
                           (cell.x)] + 1;
 
        // Update next point
        cell.x = nx;
        cell.y = ny;
 
        return cell;
    }
 
    /* displays the chessboard with all the
    legal knight's moves */
    void print(int a[])
    {
        for (int i = 0; i < N; ++i)
        {
            for (int j = 0; j < N; ++j)
                System.out.printf("%d\t", a[j * N + i]);
            System.out.printf("\n");
        }
    }
 
    /* checks its neighbouring squares */
    /* If the knight ends on a square that is one
    knight's move from the beginning square,
    then tour is closed */
    boolean neighbour(int x, int y, int xx, int yy)
    {
        for (int i = 0; i < N; ++i)
            if (((x + cx[i]) == xx) &&
                ((y + cy[i]) == yy))
                return true;
 
        return false;
    }
 
    /* Generates the legal moves using warnsdorff's
    heuristics. Returns false if not possible */
    boolean findClosedTour()
    {
        // Filling up the chessboard matrix with -1's
        int a[] = new int[N * N];
        for (int i = 0; i < N * N; ++i)
            a[i] = -1;
 
        // initial position
        int sx = 3;
        int sy = 2;
 
        // Current points are same as initial points
        Cell cell = new Cell(sx, sy);
 
        a[cell.y * N + cell.x] = 1; // Mark first move.
 
        // Keep picking next points using
        // Warnsdorff's heuristic
        Cell ret = null;
        for (int i = 0; i < N * N - 1; ++i)
        {
            ret = nextMove(a, cell);
            if (ret == null)
                return false;
        }
 
        // Check if tour is closed (Can end
        // at starting point)
        if (!neighbour(ret.x, ret.y, sx, sy))
            return false;
 
        print(a);
        return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // While we don't get a solution
        while (!new GFG().findClosedTour())
        {
            ;
        }
    }
}
 
class Cell
{
    int x;
    int y;
 
    public Cell(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}
 
// This code is contributed by SaeedZarinfam


Python3




# Python program to for Knight's tour problem using
# Warnsdorff's algorithm
import random
 
class Cell:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
N = 8
 
# Move pattern on basis of the change of
# x coordinates and y coordinates respectively
cx = [1, 1, 2, 2, -1, -1, -2, -2]
cy = [2, -2, 1, -1, 2, -2, 1, -1]
 
# function restricts the knight to remain within
# the 8x8 chessboard
def limits(x, y):
    return ((x >= 0 and y >= 0) and (x < N and y < N))
 
# Checks whether a square is valid and empty or not
def isempty(a, x, y):
    return (limits(x, y)) and (a[y * N + x] < 0)
 
# Returns the number of empty squares adjacent to (x, y)
def getDegree(a, x, y):
    count = 0
    for i in range(N):
        if isempty(a, (x + cx[i]), (y + cy[i])):
            count += 1
    return count
 
# Picks next point using Warnsdorff's heuristic.
# Returns false if it is not possible to pick
# next point.
def nextMove(a, cell):
    min_deg_idx = -1
    c = 0
    min_deg = (N + 1)
    nx = 0
    ny = 0
 
    # Try all N adjacent of (*x, *y) starting
    # from a random adjacent. Find the adjacent
    # with minimum degree.
    start = random.randint(0, 1000) % N
    for count in range(0, N):
        i = (start + count) % N
        nx = cell.x + cx[i]
        ny = cell.y + cy[i]
        c = getDegree(a, nx, ny)
        if ((isempty(a, nx, ny)) and c < min_deg):
            min_deg_idx = i
            min_deg = c
 
    # IF we could not find a next cell
    if (min_deg_idx == -1):
        return None
 
    # Store coordinates of next point
    nx = cell.x + cx[min_deg_idx]
    ny = cell.y + cy[min_deg_idx]
 
    # Mark next move
    a[ny * N + nx] = a[(cell.y) * N + (cell.x)] + 1
 
    # Update next point
    cell.x = nx
    cell.y = ny
 
    return cell
 
# displays the chessboard with all the legal knight's moves
def printA(a):
    for i in range(N):
        for j in range(N):
            print("%d\t" % a[j * N + i], end="")
        print()
 
# checks its neighbouring squares
# If the knight ends on a square that is one knight's move from the beginning square,then tour is closed
def neighbour(x, y, xx, yy):
    for i in range(N):
        if ((x + cx[i]) == xx) and ((y + cy[i]) == yy):
            return True
    return False
 
#  Generates the legal moves using warnsdorff's heuristics. Returns false if not possible
def findClosedTour():
    # Filling up the chessboard matrix with -1's
    a = [-1] * N * N
 
    # initial position
    sx = 3
    sy = 2
 
    # Current points are same as initial points
    cell = Cell(sx, sy)
 
    a[cell.y * N + cell.x] = 1  # Mark first move.
 
    # Keep picking next points using Warnsdorff's heuristic
    ret = None
    for i in range(N * N - 1):
        ret = nextMove(a, cell)
        if ret == None:
            return False
 
    # Check if tour is closed (Can end at starting point)
    if not neighbour(ret.x, ret.y, sx, sy):
        return False
    printA(a)
    return True
 
 
# Driver Code
if __name__ == '__main__':
    # While we don't get a solution
    while not findClosedTour():
        pass
 
# This code is contributed by Tapesh(tapeshdua420)


C#




//C# program for Knight’s tour 
//problem using Warnsdorff’salgorithm
using System;
using System.Collections;
using System.Collections.Generic;
 
public class GFG{
     
    public static int N = 8;
  
    // Move pattern on basis of the change of
    // x coordinates and y coordinates respectively
    public int[] cx = new int[] {1, 1, 2, 2, -1, -1, -2, -2};
    public int[] cy = new int[] {2, -2, 1, -1, 2, -2, 1, -1};
  
    // function restricts the knight to remain within
    // the 8x8 chessboard
    bool limits(int x, int y)
    {
        return ((x >= 0 && y >= 0) && (x < N && y < N));
    }
  
    /* Checks whether a square is valid and
    empty or not */
    bool isempty(int[] a, int x, int y)
    {
        return ((limits(x, y)) && (a[y * N + x] < 0));
    }
 
    /* Returns the number of empty squares
    adjacent to (x, y) */
    int getDegree(int[] a, int x, int y)
    {
        int count = 0;
        for (int i = 0; i < N; ++i)
            if (isempty(a, (x + cx[i]),
                           (y + cy[i])))
                count++;
  
        return count;
    }
     
    // Picks next point using Warnsdorff's heuristic.
    // Returns false if it is not possible to pick
    // next point.
    Cell nextMove(int[] a, Cell cell)
    {
        int min_deg_idx = -1, c,
            min_deg = (N + 1), nx, ny;
  
        // Try all N adjacent of (*x, *y) starting
        // from a random adjacent. Find the adjacent
        // with minimum degree.
        Random random = new Random();
        int start=random.Next(0, 1000);
        for (int count = 0; count < N; ++count)
        {
            int i = (start + count) % N;
            nx = cell.x + cx[i];
            ny = cell.y + cy[i];
            if ((isempty(a, nx, ny)) &&
                (c = getDegree(a, nx, ny)) < min_deg)
            {
                min_deg_idx = i;
                min_deg = c;
            }
        }
  
        // IF we could not find a next cell
        if (min_deg_idx == -1)
            return null;
  
        // Store coordinates of next point
        nx = cell.x + cx[min_deg_idx];
        ny = cell.y + cy[min_deg_idx];
  
        // Mark next move
        a[ny * N + nx] = a[(cell.y) * N +
                           (cell.x)] + 1;
  
        // Update next point
        cell.x = nx;
        cell.y = ny;
  
        return cell;
    }
  
    /* displays the chessboard with all the
    legal knight's moves */
    void print(int[] a)
    {
        for (int i = 0; i < N; ++i)
        {
            for (int j = 0; j < N; ++j)
                Console.Write(a[j * N + i]+"\t");
            Console.Write("\n");
        }
    }
     
    /* checks its neighbouring squares */
    /* If the knight ends on a square that is one
    knight's move from the beginning square,
    then tour is closed */
    bool neighbour(int x, int y, int xx, int yy)
    {
        for (int i = 0; i < N; ++i)
            if (((x + cx[i]) == xx) &&
                ((y + cy[i]) == yy))
                return true;
  
        return false;
    }
  
    /* Generates the legal moves using warnsdorff's
    heuristics. Returns false if not possible */
    bool findClosedTour()
    {
        // Filling up the chessboard matrix with -1's
        int[] a = new int[N * N];
        for (int i = 0; i < N * N; ++i)
            a[i] = -1;
  
        // initial position
        int sx = 3;
        int sy = 2;
  
        // Current points are same as initial points
        Cell cell = new Cell(sx, sy);
  
        a[cell.y * N + cell.x] = 1; // Mark first move.
  
        // Keep picking next points using
        // Warnsdorff's heuristic
        Cell ret = null;
        for (int i = 0; i < N * N - 1; ++i)
        {
            ret = nextMove(a, cell);
            if (ret == null)
                return false;
        }
  
        // Check if tour is closed (Can end
        // at starting point)
        if (!neighbour(ret.x, ret.y, sx, sy))
            return false;
  
        print(a);
        return true;
    }
     
    static public void Main (){
        // While we don't get a solution
        while (!new GFG().findClosedTour())
        {
            ;
        }
    }
}
 
class Cell
{
    public int x;
    public int y;
  
    public Cell(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}
 
//This code is contributed by shruti456rawal


Javascript




// JavaScript program to for Knight's tour problem using
// Warnsdorff's algorithm
class Cell {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}
 
const N = 8;
 
// Move pattern on basis of the change of
// x coordinates and y coordinates respectively
const cx = [1, 1, 2, 2, -1, -1, -2, -2];
const cy = [2, -2, 1, -1, 2, -2, 1, -1];
 
// function restricts the knight to remain within
// the 8x8 chessboard
function limits(x, y) {
    return ((x >= 0 && y >= 0) && (x < N && y < N));
}
// Checks whether a square is valid and empty or not
function isempty(a, x, y) {
    return (limits(x, y)) && (a[y * N + x] < 0);
}
 
// Returns the number of empty squares adjacent to (x, y)
function getDegree(a, x, y) {
    let count = 0;
    for (let i = 0; i < N; i++) {
        if (isempty(a, (x + cx[i]), (y + cy[i]))) {
            count += 1;
        }
    }
    return count;
}
 
// Picks next point using Warnsdorff's heuristic.
// Returns false if it is not possible to pick
// next point.
function nextMove(a, cell) {
    var min_deg_idx = -1;
    var c = 0;
    var min_deg = (N + 1);
    var nx = 0;
    var ny = 0;
     
    // Try all N adjacent of (*x, *y) starting
    // from a random adjacent. Find the adjacent
    // with minimum degree.
    var start = Math.floor(Math.random() * 1000) % N;
    for (var count = 0; count < N; count++) {
        i = (start + count) % N;
        nx = cell.x + cx[i];
        ny = cell.y + cy[i];
        c = getDegree(a, nx, ny);
        if ((isempty(a, nx, ny)) && c < min_deg) {
            min_deg_idx = i;
            min_deg = c;
        }
    }
      
    // IF we could not find a next cell 
    if (min_deg_idx == -1) {
        return null; 
    }   
     
    // Store coordinates of next point
    nx = cell.x + cx[min_deg_idx];
    ny = cell.y + cy[min_deg_idx];
     
    // Mark next move
    a[ny * N + nx] = a[(cell.y) * N + (cell.x)] + 1; 
 
    // Update next point
    cell.x = nx;
    cell.y = ny;
     
    return cell;
 
}
 
// checks its neighbouring squares
// If the knight ends on a square that is one knight's move from the beginning square,then tour is closed
function neighbour(x, y, xx, yy) {
    for (var i = 0; i < N; i++) {
        if (((x + cx[i]) == xx) && ((y + cy[i]) == yy)){
            return true
        } else {
            return false
        }
    }   
}
 
//  Generates the legal moves using warnsdorff's heuristics. Returns false if not possible
function findClosedTour() {
    // Filling up the chessboard matrix with -1's
    var a = new Array(N * N).fill(-1);
     
    // initial position
    var sx = 3;
    var sy = 2;
     
    // Current points are same as initial points
    var cell = new Cell(sx, sy);
     
    a[cell.y * N + cell.x] = 1; // Mark first move.
     
    // Keep picking next points using Warnsdorff's heuristic
    var ret = null;
    for (var i = 0; i < N * N - 1; i++) {
        ret = nextMove(a, cell);
        if (ret == null) {
            return false;
        }
    }
     
    // Check if tour is closed (Can end at starting point)
    if (!neighbour(ret.x, ret.y, sx, sy)) {
        return false;
    }
    console.log(a);
    return true;
}
 
// Driver Code
// While we don't get a solution
while(!findClosedTour()){
}
 
// This code is contributed by Tapesh(tapeshdua420)


Output: 

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

Time complexity: O(N^3)
Space complexity: O(N^2)

The Hamiltonian path problem is NP-hard in general. In practice, Warnsdorff’s heuristic successfully finds a solution in linear time.

Do you know? 
“On an 8 × 8 board, there are exactly 26,534,728,821,064 directed closed tours (i.e. two tours along the same path that travel in opposite directions are counted separately, as are rotations and reflections). The number of undirected closed tours is half this number, since every tour can be traced in reverse!”

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

 



Previous Article
Next Article

Similar Reads

The Knight's tour problem
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 fo
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 &gt; 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 =&gt;
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
Widest Path Problem | Practical application of Dijkstra's Algorithm
It is highly recommended to read Dijkstra's algorithm using the Priority Queue first.Widest Path Problem is a problem of finding a path between two vertices of the graph maximizing the weight of the minimum-weight edge in the path. See the below image to get the idea of the problem: Practical Application Example: This problem is a famous variant of
10 min read
Hungarian Algorithm for Assignment Problem | Set 2 (Implementation)
Given a 2D array, arr of size N*N where arr[i][j] denotes the cost to complete the jth job by the ith worker. Any worker can be assigned to perform any job. The task is to assign the jobs such that exactly one worker can perform exactly one job in such a way that the total cost of the assignment is minimized. Example Input: arr[][] = {{3, 5}, {10,
7 min read
Ford-Fulkerson Algorithm for Maximum Flow Problem
The Ford-Fulkerson algorithm is a widely used algorithm to solve the maximum flow problem in a flow network. The maximum flow problem involves determining the maximum amount of flow that can be sent from a source vertex to a sink vertex in a directed weighted graph, subject to capacity constraints on the edges. The algorithm works by iteratively fi
15+ min read
Tiling Problem using Divide and Conquer algorithm
Given a n by n board where n is of form 2k where k &gt;= 1 (Basically n is a power of 2 with minimum value as 2). The board has one missing cell (of size 1 x 1). Fill the board using L shaped tiles. A L shaped tile is a 2 x 2 square with one cell of size 1x1 missing. Figure 1: An example inputThis problem can be solved using Divide and Conquer. Bel
15+ min read
Greedy Approximate Algorithm for Set Cover Problem
Given a universe U of n elements, a collection of subsets of U say S = {S1, S2...,Sm} where every subset Si has an associated cost. Find a minimum cost subcollection of S that covers all elements of U. Example: U = {1,2,3,4,5} S = {S1,S2,S3} S1 = {4,1,3}, Cost(S1) = 5 S2 = {2,5}, Cost(S2) = 10 S3 = {1,4,3,2}, Cost(S3) = 3 Output: Minimum cost of se
6 min read
Practice Tags :