I am trying to solve the knight's tour problem, but it's getting stuck in an infinite loop. I tried debugging but no change. Could someone please help me out? Thank you.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void knightMove(int x, int y, vector<vector<int>> chess, int moves) {
// check if the cell is valid to make a move
if(x<0 || x>=8 || y<0 || y>=8 || chess[x][y]!=-1) return;
// if it is valid, we put the current move number in place
chess[x][y] = moves;
// base condition to print the final answer and return
if(moves==63) {
for(int p=0; p<8; p++) {
for(int q=0; q<8; q++) {
cout << chess[p][q] << " ";
}
cout << endl;
}
chess[x][y]=-1;
return;
}
// traversal arrays
int i[] = {2,2,-2,-2,1,1,-1,-1};
int j[] = {1,-1,1,-1,2,-2,2,-2};
for(int k=0; k<8; k++) {
knightMove(x+i[k], y+j[k], chess, moves+1);
}
// backtracking
chess[x][y]=-1;
return;
}
int main() {
vector<vector<int>> chess (8, vector<int> (8,-1));
knightMove(0,0,chess, 0);
}