【发布时间】:2021-07-18 14:53:12
【问题描述】:
谁能指出代码中的缺陷? 我使用的想法是递归回溯,我想坚持这种解决给定问题的方式。当变量 move
//checking on which move was the square visited
int board[8][8] = {{1,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}};
int x = 0;//x and y coordinate of the knight's placement
int y = 0;
//move knight by
int move_to[8][8] = {{1,2},{-1,-2},{-1,2},{1,-2},{2,1},{-2,-1},{-2,1},{2,-1}};
//how many moves have been done
int moves = 0;
void solve()
{
//printing one solution
if(moves==63)
{
for(int k = 0; k < 8; k++)
{
for(int n = 0; n < 8; n++)
cout << setw(2) << board[k][n] << " ";
cout << "\n";
}
cout << "--------------------\n";
return;
}
else
{
for(int i = 0; i < 8; i++)
{
//checking if knight is not leaving the board
if(x+move_to[i][0]<0 || x+move_to[i][0]>7 || y+move_to[i][1]<0 ||
y+move_to[i][1]>7 || board[x+move_to[i][0]][y+move_to[i][1]]>0)
continue;
//moving theknight
x+=move_to[i][0];
y+=move_to[i][1];
//increasing the moves count
moves++;
//marking the square to be visited
board[x][y] = moves+1;
//backtracking
solve();
board[x][y] = 0;
x-=move_to[i][0];
y-=move_to[i][1];
moves--;
}
}
}
int main()
{
solve();
return 0;
}
【问题讨论】:
-
没有完成编译或者没有完成运行?
-
cmd.exe 在打印了几个解决方案后,打印了 '_' 所以,我认为这意味着 - 没有完成运行就是我的意思;D。会解决的。
-
编译的时候有没有开启优化?
-
你需要添加一个启发式来使这个计算可行,我似乎记得你应该移动到一个被已经访问过的正方形包围的正方形。
-
Ehm,在选择下一步时排除前一个方格是否有意义?如果没有,则无限循环。
标签: c++ algorithm recursion backtracking knights-tour