我写了一个实现来解决C ++中的骑士之旅,即使对于像8这样的小值,它似乎也花费了太长时间。我使用的是大多数书籍中所示的基本回溯方法,并且in_board和unvisited函数检查是否移动制作在木板间内,到现在为止都没有访问。
移动向量包含如下对
{-1,2},{-1,-2},{1,{2,-1},1},{-2,
bool
knights_tour(vector < vector <int> > &board,int x,int y,int d)
{
int new_x,new_y;
if (d == board.size()*board.size())
{
print_board(board,"Here is a solution");
return true;
}
for (auto move : moves)
{
new_x = x + move.first;
new_y = y + move.second;
if (in_board(board,new_x,new_y) && unvisited(board,new_y))
{
board[new_x][new_y] = d;
if (knights_tour(board,new_y,d+1))
return true;
else
board[new_x][new_y] = -1;
}
}
return false;
}
int main()
{
int n;
cin >> n;
vector <vector <int>> board(n,vector <int> (n,-1));
board[0][0] = 0;
cout << board.size()*board.size();
knights_tour(board,1);
}