我写下了骑士巡回问题的代码,我不知道解决方案的实际问题是什么,它可以正常运行直到n = 6,但是在那之后,要花很长时间才能运行。它显示正确的输出,但是要花很长时间,因为我将n = 7或n = 8或更高。这是我的代码:
#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;
}