【发布时间】:2020-08-28 20:41:18
【问题描述】:
N Queen 问题的行为不恰当,即它在使用 long long int 时给出了一些输出(虽然不正确),但在 int 的情况下,它给出了所有元素为 -1 的板数组。
代码是:
#include<iostream>
#include<iomanip>
#include<cstring>
using namespace std;
const int d=4;
//fills 0 to all the positions that are unsafe due to queen placed at (x,y)
void fill(int board[d][d],int x,int y){
for (int i = 0; i < d; ++i)
{
//for row and column
board[i][y]=0;
board[x][i]=0;
}
//for the diagonal following i-1 & j-1 pattern
for(int i=x,j=y; i>=0 && j>=0 ; --i,--j){
board[i][j]=0;
}
//for the diagonal following i+1 & j+1 pattern
for(int i=x,j=y; i<d && j<d ; ++i,++j){
board[i][j]=0;
}
//for the diagonal following i-1 & j+1 pattern
for(int i=x,j=y; i>=0 && j<d ; --i,++j){
board[i][j]=0;
}
//for the diagonal following i+1 & j-1 pattern
for(int i=x,j=y; i<d && j>=0 ; ++i,--j){
board[i][j]=0;
}
}
//fills -1, i.e. clears the positions that were filled earlier due to queen at (x,y)
void unfill(int board[d][d],int x,int y){
for (int i = 0; i < d; ++i)
{
board[i][y]=-1;
board[x][i]=-1;
}
for(int i=x,j=y; i>=0 && j>=0 ; --i,--j){
board[i][j]=-1;
}
for(int i=x,j=y; i<d && j<d ; ++i,++j){
board[i][j]=-1;
}
for(int i=x,j=y; i>=0 && j<d ; --i,++j){
board[i][j]=-1;
}
for(int i=x,j=y; i<d && j>=0 ; ++i,--j){
board[i][j]=-1;
}
}
void printboard(int board[d][d]){
for (int i = 0; i < d; ++i)
{
for (int j = 0; j < d; ++j)
{
cout<<setw(3)<<board[i][j]<<" ";
}cout<<endl;
}
}
bool solve(int board[d][d],int queenno,int x,int y){
//Returns true if all the queens are placed properly
if(queenno==4){
return true;
}
for (int i = x; i < d; ++i)
{
for (int j = y; j < d; ++j)
{
// If the position is unoccupied or safe i.e. value is -1
if(board[i][j]==-1){
fill(board,i,j); //assigns 0 to the places that are unsafe due to queen
board[i][j]=1; // places the queen at i,j
queenno++;
bool ans=solve(board,queenno,i,j);
if(ans==false){
unfill(board,i,j); // assigns -1, i.e. backtracks
queenno--;
board[i][j]=-1; // clears the earlier position of the queen
}
}
}
}
// If can't place all the queens return false
if(x==d-1 && y==d-1 && queenno<4){
return false;
}
}
int main()
{
// Creating a board of size 4x4 and assigning -1 to all its element
int board[d][d];
memset(board,-1,sizeof(board));
bool ans=solve(board,0,0,0);
if(ans)
printboard(board);
else
cout<<"Can't print";
return 0;
}
使用 long long int 时给出的输出(虽然错误)是
0 -1 0 -1
0 0 0 -1
1 0 0 0
0 0 1 0
请说明回溯出错的地方以及为什么在使用 int 而不是 long long int 时程序没有输出(即所有元素 -1)。
【问题讨论】:
-
How to debug small programs。使用调试器并单步执行您的代码,以查看代码在何处采用与您计划不同的路径,或变量设置为您未预期的值。
-
N-Queens 可以在多项式时间内求解。您使用回溯是有原因的吗?
-
@WillemVanOnsem 我只是在学习回溯。你能告诉回溯哪里出错了吗?
标签: c++ c algorithm c++11 c++14