-1

I am getting a infinite loop when I try and run my solution for the Knights Tour problem using Backtracking

My Solution Code: Link: https://ideone.com/Ud92vF code:

#include <bits/stdc++.h> 
using namespace std;
bool valid(int arr[8][8],int r,int c)
{
    if(r>=0 and r<8 and c>=0 and c<8 and arr[r][c]== -1)
        return true;
    return false;
}
void fun(int arr[8][8],int r,int c,int x)
{
    if(x==64){
    cout<<"***********************ARRAY FOUND***********************\n";
    for(int i=0;i<8;i++){
        for(int j=0;j<8;j++)
            cout<<arr[i][j]<<" ";
        cout<<"\n";
        }
        return;
    }
    if(!valid(arr,r,c))
    return;
    arr[r][c] = x;
    fun(arr,r-2,c+1,x+1); fun(arr,r-2,c-1,x+1);
    fun(arr,r-2,c+2,x+1); fun(arr,r-2,c-2,x+1);
    fun(arr,r+2,c+1,x+1); fun(arr,r+2,c-1,x+1);
    fun(arr,r+1,c+2,x+1); fun(arr,r+1,c-2,x+1);
    arr[r][c] = -1;
} 

int main() 
{
    int arr[8][8] ;
    for(int i=0;i<8;i++){
        for(int j=0;j<8;j++)
            arr[i][j] = -1;
    }
    int r=0,c=0,x=0; fun(arr,r,c,x);
} 
Jeffrey
  • 11,063
  • 1
  • 21
  • 42

1 Answers1

0

Make sure your move array is correct:

fun(arr,r-2,c-1,x+1); fun(arr,r-2,c+1,x+1);
fun(arr,r-1,c-2,x+1); fun(arr,r-1,c+2,x+1);
fun(arr,r+1,c-2,x+1); fun(arr,r+1,c+2,x+1);
fun(arr,r+2,c-1,x+1); fun(arr,r+2,c+1,x+1);

With this I get a right answer:

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

Note that as you use the 65th move to validate you answer, you'll get 8 of the same correct answers in a row. And then another 8. Etc. You can fix this by printing after your 64th move:

void fun(int arr[8][8],int r,int c,int x)
{
    if(!valid(arr,r,c))
    return;

    arr[r][c] = x;

    if(x==63){
    cout<<"***********************ARRAY FOUND***********************\n";
    for(int i=0;i<8;i++){
        for(int j=0;j<8;j++)
            cout<<arr[i][j]<<" ";
        cout<<"\n";
        }
    }
    else
    {
        fun(arr,r-2,c-1,x+1); fun(arr,r-2,c+1,x+1);
        fun(arr,r-1,c-2,x+1); fun(arr,r-1,c+2,x+1);
        fun(arr,r+1,c-2,x+1); fun(arr,r+1,c+2,x+1);
        fun(arr,r+2,c-1,x+1); fun(arr,r+2,c+1,x+1);
    }
    arr[r][c] = -1;
} 

And one last issue is that you only ever start at {0,0} so you'll only find knights tours which start on that square. You really want to start from every square to find all possible knights tours. Or if you're feeling clever you only need to check a subset of the starting squares and use symmetry to generate the others.

Mike Vine
  • 9,468
  • 25
  • 44