c++ - NQUEENS问题的C++递归解决方案无法正常工作
问题描述
我正在尝试使用向量和类在 C++ 中使用回溯来解决著名的NQUEENS问题。但它在某些情况下(例如 5)和剩余(例如 4)给出了正确的结果,它显示“解决方案不存在”。
我的代码如下: 用于存储皇后位置的行和列的类声明。
class position
{
public:
int r,c;
position(int r,int c)
{
this->r=r;
this->c=c;
}
};
递归函数:
vector<position> positions;
bool solve(int n, int r)
{
if(r==n)
return true;
for (int c = 0; c < n; ++c)
{
bool safe=true;
for(int q=0;q<r;++q)
{
if (positions[q].c == c || positions[q].r - positions[q].c == r - c
|| positions[q].r + positions[q].c == r + c)
{
safe = false;
break;
}
}
if(safe)
{
position p(r,c);
positions.push_back(p);
if(solve(n,r+1))
return true;
}
}
return false;
}
驱动函数如下:
int main()
{
int n;
cin>>n;
if(!solve(n,0))
{
cout<<"Solution doesn't exist"<<endl;
return 0;
}
printboard(n);
return 0;
}
请帮我解决这个问题。
解决方案
if(solve(n,r+1))
return true;
else
positions.erase(positions.begin()+positions.size()-1);
如果一个单元格的解决方案不存在,则从可能的位置擦除该单元格,以避免冲突。编辑:- 感谢 Bo R 先生的更正。
推荐阅读
- amazon-web-services - 使用 AWS DMS 从 SQL Server 迁移到 S3(csv) 后文件大小显着减小
- r - 比较R中不同长度的两个数据帧
- javascript - 为什么函数调用首先在以下js代码的函数声明和描述之前起作用?
- vim - Vim:避免在成功制作后按 ENTER 键?
- c# - 将 sql 查询转换为 linq,以便我可以在 foreach 循环中使用它
- python - 无法修复错误:OpenCV(4.1.2) esize.cpp:3720: error: (-215:Assertion failed) !ssize.empty() in function 'resize'
- io - 为什么输入流有副作用?
- javascript - FB Javascript 登录 SDK 的问题
- sql - larave:当计数达到给定值时如何从 foreach 循环中删除选定的数据
- laravel - 为什么我在 Laravel 8 身份验证中的尝试()方法上收到错误(在智能 VSCode 中),内容为:未定义的方法“尝试”