I wrote down the code for knight tour problem, I couldn't figure out what is the actual issue with the solution, it's running fine upto n=6, but after that, it is taking a long time to run. It's showing correct output but taking a really long time as I put n=7 or n=8 or higher. Here's my code :
#include<bits/stdc++.h>
using namespace std;
bool isSafe(vector<vector<int>> sol, int x, int y){
int n=sol.size();
return (x>=0 && x<n && y>=0 && y<n && sol[x][y]==-1);
}
bool findSolUtil(vector<vector<int>> &sol, vector<int> xMoves, vector<int> yMoves, int x, int y, int count){
int n=sol.size(), i, next_x, next_y;
if(count==n*n){
return true;
}
for(i=0; i<8; i++){
next_x = x+xMoves[i];
next_y = y+yMoves[i];
if(isSafe(sol, next_x, next_y)){
sol[next_x][next_y] = count;
if(findSolUtil(sol, xMoves, yMoves, next_x, next_y, count+1)){
return true;
}
sol[next_x][next_y] = -1;
}
}
return false;
}
void findSol(int n){
vector<vector<int>> sol(n, vector<int>(n, -1));
vector<int> xMoves = {2, 1, -1, -2, -2, -1, 1, 2};
vector<int> yMoves = {1, 2, 2, 1, -1, -2, -2, -1};
sol[0][0] = 0;
cout << findSolUtil(sol, xMoves, yMoves, 0, 0, 1);
}
int main(){
int n;
cout << "Size of the board is nXn, enter n : ";
cin >> n;
findSol(n);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire