如何解决Knight's Tour 中的无限循环使用 C++
我正在尝试解决骑士的旅行问题,但它陷入了无限循环。我试过调试但没有改变。有人可以帮我吗?谢谢。
#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,1,-1,-1};
int j[] = {1,-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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。