This code is not giving any output. It should output a matrix of 8X8 size.
#include <iostream>
#define N 8
using namespace std;
This function prints the matrix:
void print(int arr[][N]){
int i, j;
for (i = 0; i < N; i++){
for (j = 0; j < N; j++)
cout<<arr[i][j]<<" ";
cout<<endl;
}
}
This function checks limits of x and y and whether knight already visited that place or not.
bool safe(int x, int y, int arr[][N]){
if(x>=0 && y>=0 && x<N && y<N && arr[x][y] == 0){
return true;
}
return false;
}
This function do most of the things:
bool solveKT(int x, int y, int movei, int arr[][N], int xmove[], int ymove[] ){
if(movei == (N*N)+1){
return true;
}
for(int k=0 ; k<8 ; k++){
int nextx = x + xmove[k];
int nexty = y + ymove[k];
if(safe(nextx, nexty, arr) == true){
arr[nextx][nexty] = movei;
if(solveKT(nextx, nexty, movei+1, arr, xmove, ymove) == true){
return true;
}
arr[nextx][nexty] = 0; // backtrack
}
}
return false;
}
This is just a driver function:
int main(){
int arr[N][N]={0};
int xmove[] = {1, 1,2, 2,-1,-1,-2,-2};
int ymove[] = {2,-2,1,-1, 2,-2, 1,-1};
arr[0][0] = 1;
int movei = 2;
bool a = solveKT(0, 0, movei, arr, xmove, ymove);
if(a == true){
print(arr);
}
else
cout<<"no solution";
}