Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

6/4/2016 Backtracking 

| Set 1 (The Knight's tour problem) ­ GeeksforGeeks

GeeksforGeeks
A computer science portal for geeks
 

Placements   Practice   GATE CS   IDE   Q&A


GeeksQuiz
Login/Register

Backtracking | Set 1 (The Knight’s tour problem)
Backtracking  is  an  algorithmic  paradigm  that  tries  different  solutions  until  finds  a  solution  that  “works”.
Problems  which  are  typically  solved  using  backtracking  technique  have  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  in  incremental  way  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. 
The 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.

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 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 work out then we go to 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.

http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 1/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks

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<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 */
bool 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.  */
bool solveKT()
{
    int sol[N][N];
 
    /* Initialization of solution matrix */
    for (int x = 0; x < N; x++)
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 2/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks
    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) == false)
    {
        printf("Solution does not exist");
        return false;
    }
    else
        printSolution(sol);
 
    return true;
}
 
/* 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 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) == true)
             return true;
         else
             sol[next_x][next_y] = ‐1;// backtracking
       }
   }
 
   return false;
}
 
/* Driver program to test above functions */
int main()
{
    solveKT();
    return 0;
}
Run on IDE

Java
// Java program for Knight Tour problem
class KnightTour {
    static int N = 8;
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 3/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks
    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;
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 4/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks
                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 program to test above functions */
    public static void main(String args[]) {
        solveKT();
    }
}
// This code is contributed by Abhishek Shankhadhar
Run on IDE

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 

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

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

Please write comments if you find anything incorrect, or you want to share more information about the topic
discussed above.

88 Comments  Category:  Backtracking  Tags:  Backtracking

Related Posts:
Find if there is a path of more than k length from a source
Fill two instances of all numbers from 1 to n in a specific way
Backtracking | Set 8 (Solving Cryptarithmetic Puzzles)
Print all possible paths from top left to bottom right of a mXn matrix
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 5/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks

Tug of War
Backtracking | Set 7 (Sudoku)
Backtracking | Set 5 (m Coloring Problem)
Backtracking | Set 4 (Subset Sum)

(Login to Rate and Mark)  

Average Difficulty : 3.4/5.0   Add to TODO List
3.4  Based on 17 vote(s)  
 

 Mark as DONE

Like Share 30 people like this. Be the first of your friends.


 
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.

88 Comments GeeksforGeeks 
1  Login

  Recommend  8 ⤤ Share Sort by Newest

Join the discussion…

karan  •  14 days ago
#include<stdio.h>
void main()
{
int row,col,x,y,tr,tc,counter=1,lowest=100,i,j; 
int cb[8][8]={0};
int horizontal[8]={1,1,­1,­1,2,2,­2,­2}; 
int vertical[8]={2,­2,2,­2,­1,1,­1,1};
int ah[8][8]={2,3,4,4,4,4,3,2, //accessibility hueristic
3,4,6,6,6,6,4,3, 
4,6,8,8,8,8,6,4,
4,6,8,8,8,8,6,4,
4,6,8,8,8,8,6,4, 
4,6,8,8,8,8,6,4,
3,4,6,6,6,6,4,3,
2,3,4,4,4,4,3,2};

printf("enter initial position\nrow : ");
scanf("%1d",&row);

see more

△  ▽ • Reply • Share › 

Nick Frazier  •  25 days ago
Why are xMove and yMove passed down recursively as arguments? Aren't they
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 6/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks
Why are xMove and yMove passed down recursively as arguments? Aren't they
constants, and if so couldn't they just be referenced globally (like N)?
△  ▽ • Reply • Share › 

Shiva Kumar  •  2 months ago
In C++: 
http://code.geeksforgeeks.org/...
△  ▽ • Reply • Share › 

Raj  •  3 months ago
We need to ensure that xMove and yMove co­ordinates form an anti­clockwise circle
starting from bottom right. Else, the problem seems like a never ending solution.

The reason above works, successors are spread far across and the number of
conflicts are also reduced.

In other words, if you change your corner from 0,0 to any other corners, it is advisable
to change your xMove and yMove arrays to represent new circle resulting in fewer
collisions.
1 △   ▽ • Reply • Share › 

P V Sai Krishna > Raj  •  3 months ago
Hi Raj,

I experienced the same what you told about never ending solution.
But according to logic it should not be a never ending solution.
Can you tell me why it is going as a infinite loop?
△  ▽ • Reply • Share › 

icemann  •  4 months ago
I started the traversal from position 5,5. I didn't change anything else. Program looks
like never ending. Is there any logic to create different move sequence for different
starting positions?

Got results after one and a half days.

­bash­4.1$ cc ­std=c99 myKT.c 
­bash­4.1$ ./a.out
56 25 44 39 20 5 60 63
45 38 57 22 59 62 19 4
26 55 24 43 40 21 6 61
37 46 41 58 23 8 3 18
54 27 36 47 42 17 12 7
35 32 51 28 15 0 9 2
50 53 30 33 48 11 16 13 
31 34 49 52 29 14 1 10
1 △   ▽ • Reply • Share › 

http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 7/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks

AllergicToBitches > icemann  •  3 months ago
I think its always better to start from any corner of matrix. If you start from
somewhere middle, knight can go to 8 different directions. If we start from
corner, the knight can go to only two points from there. Since the algorithm is
exponential, optimized input to it can make huge difference.
1 △   ▽ • Reply • Share › 

abhishek  •  6 months ago
similar solution for 
http://algorithms.tutorialhori...
http://ideone.com/Ur46R
△  ▽ • Reply • Share › 

sai  •  9 months ago
can some one explain why we have not decremented movei when we backtrack
△  ▽ • Reply • Share › 

the_killer > sai  •  9 months ago
movi will automatically get decremented when all the calls of for loop fail and
stack would unwind to previous movi value not just movi but nextx,nexty and
rest stack arguments also (i.e. we are discarding our move by doing sol[next_x]
[next_y] = ­1)
1 △   ▽ • Reply • Share › 

rishabh goel  •  10 months ago
Same code is not working when i change xMove to {1,2,­1,1,­1,2,­2,­2} and yMove to
{2,1,2,­2,­2,­1,­1,1}

The moves are same , i have just changed the indices !
△  ▽ • Reply • Share › 

Rajan Parmar > rishabh goel  •  5 months ago
as you said to "Sheena" below : the configuration in solution is clearly circular
and hence faster, your configuration is quite abrupt and so should take more
time. By circular I mean if you plot the 1st vector, the 2nd vector will be in
clockwise or anticlockwise direction and so will be the 3rd, 4th, 5th so on..
△  ▽ • Reply • Share › 

user2345 > rishabh goel  •  6 months ago
yes ! I have tested what you said. it is really amazing!! why does it happen?
△  ▽ • Reply • Share › 

Joy  •  a year ago
Above code has small compilation bug for older C compilers. 'for' loop initial
declarations are only allowed in C99 mode. for (int x = 0; x < N; x++).
△  ▽ • Reply • Share › 

http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 8/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks

codelearner  •  a year ago
can anyone expalin the xmove and ymove arrays .. why and how they have bee used?
1 △   ▽ • Reply • Share › 

Nexus > codelearner  •  a year ago
It contains possible moves of Knight’s from its position.  
Please read :

https://en.wikipedia.org/wiki/...
1 △   ▽ • Reply • Share › 

Sheena Chhabra  •  a year ago
int x_move[8]={1,1,2,2,­1,­1,­2,­2};

int y_move[8]={2,­2,1,­1,2,­2,1,­1};

when i am using these array. it is running infinite loop ...can anyone explain??
3 △   ▽ • Reply • Share › 

Rajan Parmar > Sheena Chhabra  •  5 months ago
It is because the order used in above mentioned solution is optimum . It get the
vacant position in one or two moves. But in your case knight is backtracking a
lot . Imagine what if your order explore all possible moves i.e 64C8 (no. of ways
8 position can be selected from 64 available position) = 4426165368 ( around
4*10^9) it will take a huge amount of tie more than 5 seconds to explore the all
position. Hence this order taking so much time .
1 △   ▽ • Reply • Share › 

rishabh goel > Sheena Chhabra  •  10 months ago
the configuration in solution is clearly circular and hence faster, your
configuration is quite abrupt and so should take more time. By circular I mean if
you plot the 1st vector, the 2nd vector will be in clockwise or anticlockwise
direction and so will be the 3rd, 4th, 5th so on..
2 △   ▽ • Reply • Share › 

sahil  •  a year ago
can you help me to analyize the time complexity of this backtrack solutin???
△  ▽ • Reply • Share › 

HuntXT > sahil  •  a year ago
You can analyse like this:

For each cell we have 8 possibilities,
and this is for each and every cell, 
so total cells = (n*n) ­1 [removing the last one]
=n^2­1
So, total complexity = O(8^(no of cells))
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 9/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks
So, total complexity = O(8^(no of cells))
= O(8^(n^2­1))
△  ▽ • Reply • Share › 

Himanshu Nandeshwar > HuntXT  •  a year ago
I understood your approach but can you please explain why (8^(n^2­1)
and not 8*(n^2­1) ? i.e why haven't you multiplied 8 ?
△  ▽ • Reply • Share › 

HuntXT > Himanshu Nandeshwar  •  a year ago
That's simple.
See, for first cell ­­­ 8 ; second ­­­­ 8 , and so on...
Now, 8 for first AND 8 for second AND 8 for third , and so on.... 
Also, for each AND we use * not + , if it had been OR then we
would have used +.

=> 8*8*8....

=>8^(n^2­1).
Also, more precisely, 8 combinations of first with 8 combinations
of second , 8 combinations of third and so on..., hence 8^(*)

Like, for example what's the total no. of color combination we
can have if we have 8 colors and 2 persons can choose any
color. 
=> first person 8, second person 8
=> total 8*8,
not 8+8.
1 △   ▽ • Reply • Share › 

Himanshu Nandeshwar > HuntXT  •  a year ago
Thankyou very much now everything is clear :)
△  ▽ • Reply • Share › 

Jeff  •  a year ago
For these move array, the program is not terminating 
int x_arr[8] = {1, ­1, ­2, ­2, ­1, 1, 2, 2};
int y_arr[8] = {2, 2, 1, ­1, ­2, ­2, ­1, 1};
http://ideone.com/IfSAm1

Anyone know the problem?
△  ▽ • Reply • Share › 

Rajan Parmar > Jeff  •  5 months ago
It is because the order used in mentioned solution is optimum . It get the vacant
position in one or two moves. But in your case knight is backtracking a lot .
Imagine what if your order explore all possible moves i.e 64C8 (no. of ways 8
position can be selected from 64 available position) = 4426165368 ( around
4*10^9) it will take a huge amount of tie more than 5 seconds to explore the all
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 10/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks

4*10^9) it will take a huge amount of tie more than 5 seconds to explore the all
position. Hence this order taking so much time.
△  ▽ • Reply • Share › 

Jeff > Jeff  •  a year ago
It Seems the first entry must be (2,1), otherwise the program won't work!!!!
1 △   ▽ • Reply • Share › 

radek  •  a year ago
in the issafe function is there a need to specify "x>0 && y>0 " since we are not
decreasing the values of x and y as such ?
△  ▽ • Reply • Share › 

Ashwani Kumar > radek  •  a year ago
the possible moves may take our knight out of board if we do not check for > 0
conditions just as we check for < N condtion
△  ▽ • Reply • Share › 

Paritosh Agrawal  •  a year ago
NOT WORKING!!
above solution is not working if i start from (0,4) instead of (0,0)
but there exist a solution for (0,4) 
http://en.wikipedia.org/wiki/K...

plz someone give the solution which works on all the cases
1 △   ▽ • Reply • Share › 

Vikram Ojha  •  a year ago
man wat r dese magic numbers 
int xMove[8] = { 2, 1, ­1, ­2, ­2, ­1, 1, 2 };
int yMove[8] = { 1, 2, 2, 1, ­1, ­2, ­2, ­1 };
△  ▽ • Reply • Share › 

Renée > Vikram Ojha  •  a year ago
Those are the 8 moves a Knight can make.
Consider negative xMove: move up; positive xMove: move down.
Also, consider negative yMove: move to the left; positive yMove: move to the
right.
A chess board has numbers and letters on its sides, but a matrix has only
numbers, so you calculate the coordinates to move up and down and
sideways.
2 down, 1 right
1 down, 2 right
1 up, 2 right
...
Did you get it?
1 △   ▽ • Reply • Share › 
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 11/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks
1 △   ▽ • Reply • Share › 

Devanshu Garg > Renée  •  3 months ago
srry but i didn't get it ?????
△  ▽ • Reply • Share › 

Vikram Ojha > Renée  •  a year ago
Ya Reene on very dat day I had seen ur previous comment and dat was
realy helpful...bt still thanx for replying
△  ▽ • Reply • Share › 

Tejwinder  •  a year ago
Do you know it makes a "Tessellation" while traversal

http://www.borderschess.org/KT...
1 △   ▽ • Reply • Share › 

Avishek Sachan  •  2 years ago
// NON RECURSIVE APPROACH and Modified solveKTUtil function

#include <stack>

#include <stdio.h>
using namespace std;

#define N 8

typedef struct Point

int x;

int y;

} SChessXY;

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

see more

△  ▽ • Reply • Share › 

Coding Enthusiast > Avishek Sachan  •  a year ago
The non­recursive version does not work. It gives wrong solution where 61 and
62 are far apart. I think the stack needs more information to be pushed in.
△  ▽ • Reply • Share › 

Aveek Biswas  •  2 years ago
The program is failing if instead of 
[ int xMove[8] = { 2, 1, ­1, ­2, ­2, ­1, 1, 2 };
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 12/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks
[ int xMove[8] = { 2, 1, ­1, ­2, ­2, ­1, 1, 2 };
int yMove[8] = { 1, 2, 2, 1, ­1, ­2, ­2, ­1 }; ],

[ int xMove[8] = { 1, 2, 1, 2, ­2, ­1, ­1, ­2 };
int yMove[8] = { 2, 1, ­2, ­1, 1, 2, ­2, ­1 }; ] is used. 
The corresponding moves in x and y direction is maintained but the order is different int
the 2nd matrix. But it fails. This means the solution also depends on these two matrices
also. Could anybody plz explain the reason for this?
1 △   ▽ • Reply • Share › 

anirudh goel > Aveek Biswas  •  a year ago
i dont whether its useful now or not.. but same thing happened to me.. and it so
happens that first values of xmove and ymove should be 2 and 1 resp. and
other values can reordered. then it works fine. i dont know reason for that..
maybe its taking too much time with other starting value? just a guess.
△  ▽ • Reply • Share › 

Avishek Sachan > Aveek Biswas  •  2 years ago
I pasted the non recursive solution, it works even you change the sequence of
directions
△  ▽ • Reply • Share › 

dustbite > Aveek Biswas  •  2 years ago
Backtracking is trying every sequence of moves to find an answer. If we find an
answer, we don't try any other sequence of moves. 
So, initially from the starting point (0, 0), we have to make a choice which is
which place should the knight be landed on such that it will derive me a knight
tour. We can land on 2 possible locations (1, 2) and (2, 1). Assume that (1, 2)
doesn't give us a knight tour but (2, 1) gives. So if you try (1, 2) first, you would
reach the solution later than you would if you had chosen (2, 1). It's because
from (1, 2) there would be more choices to explore, but any of them would not
lead us to the solution(first all possible paths from (1, 2) need to be explored
before we back track and try (2, 1) which is obviously too slow.). So, if you
could prune the search path earlier, then could find solution faster. There are
some heuristics that would help us derive solution for the knight tour
efficiently(and for any N x N board if knight tour is possible).
1 △   ▽ • Reply • Share › 

ankit Aggarwal  •  2 years ago
what will be the time complexity of this algorithm?
1 △   ▽ • Reply • Share › 

Mayank > ankit Aggarwal  •  2 years ago
http://stackoverflow.com/quest...
1 △   ▽ • Reply • Share › 

Deepesh > ankit Aggarwal  •  2 years ago
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 13/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks

@Admin Plz reply
△  ▽ • Reply • Share › 

Stéphane  •  2 years ago
Has anyone tried to start from others positions than [0][0] ?
△  ▽ • Reply • Share › 

Guest > Stéphane  •  2 years ago
Yes, it is taking very long for other positions
△  ▽ • Reply • Share › 

arjomanD  •  2 years ago
Hello Every1 . I had a question . i have my code BUT it works very very Slow for N=8
(in fact i havn't still got the answer !

Would you Plz help me make my code and algorithm better ?

http://paste.ubuntu.com/742019...

Thanks !
△  ▽ • Reply • Share › 

KC  •  3 years ago
Knight moves 2 squares in the direction of one of the axes of the board, and then 1
square in an orthogonal direction. This definition can then be generalized to obtain an
(a, b) knight. If the numbers a+b and a­b are coprime, tour is also possible in non 8x8
board using this similar algorithm.
△  ▽ • Reply • Share › 

Probe  •  3 years ago
Here is also my implementation of the above algorithm for java:

[code]public class HorseTraversing{

public static void printBoard(int[][] board){
for (int i=0; i<board.length; i++){="" for="" (int="" y="0;" y<board.length;="" y++){="" if=""
(board[i][y]=""> 9){
System.out.print(board[i][y] + " ");
}else {
System.out.print(" " + board[i][y] + " ");
}
}
System.out.println();
}
}

public static boolean isSafeMove(int moveX, int moveY, int[][] board){ 
int maxPosition = (board.length ­ 1);
http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 14/15
6/4/2016 Backtracking | Set 1 (The Knight's tour problem) ­ GeeksforGeeks

see more

△  ▽ • Reply • Share › 

dark_night  •  3 years ago
I am still not getting the difference between backtracking and recursion.. especially for
this problem

Here also we are using every possible move and in recursion too we do the same , so
how does backtracking is more efficient than recursion.
2 △   ▽ • Reply • Share › 

@geeksforgeeks, Some rights reserved        Contact Us!        About Us!               Advertise with us!       

http://www.geeksforgeeks.org/backtracking­set­1­the­knights­tour­problem/ 15/15

You might also like