我正在尝试使用回溯来解决 N queen 问题,但在编译时它会给出运行时错误(动态堆栈缓冲区溢出)
I am trying to solve the N queen problem using backtracking but on compilation its giving the runtime error (dynamic-stack-buffer-overflow)
>我正在尝试使用回溯来解决"N Queen 问题",但由于某些错误,它显示运行时错误。 编译时,它显示运行时错误并给出消息dynamic-stack-buffer-overflow on address ******
多次检查代码,但找不到问题的根源
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<string> temp;
int arr[n]={0};
arr[0]=99;
vector<int> queen;
calc(result,n,temp,arr,0,queen);
return result;
}
void calc(
vector<vector<string>>& result,
int n, vector<string>& temp,
int * arr,
int count,
vector<int>& queen
) {
if(count==n)
{
for(int k=0;k<queen.size();k++)
{
string s="";
for(int m=1;m<=n;m++)
{
if(m==queen[k])
s=s+'Q';
else
s=s+'.';
}
temp.push_back(s);
}
result.push_back(temp);
}
else{
for(int i=1;i<=n;i++)
{
if(arr[i]==0)
{
int temp1[n]={0};
temp1[0]=99;
for(int j=1;j<=n;j++)
{
temp1[j]=arr[j]+temp1[j];
if(arr[j]!=0)
temp1[j+1]++;
}
queen.push_back(i);
temp1[i]++;
calc(result,n,temp,temp1,count+1,queen);
queen.pop_back();
}
}
}
}
};
for(int i=1;i<=n;i++)
{
if(arr[i]==0)
arr
的有效索引为 0 到 n-1
。在此循环的最后一次迭代中,当i == n
时,arr[i]
通过越界访问索引来表现出未定义的行为。
与temp1[j]
类似,更重要的是,temp1[j+1]
在内循环中。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- 运行时的动态函数解析
- 删除动态数组会导致运行时错误
- 我正在尝试使用回溯来解决 N queen 问题,但在编译时它会给出运行时错误(动态堆栈缓冲区溢出)
- 访问导致运行时错误的动态数组
- 在动态内存分配中出现运行时错误
- 动态分配数组中的运行时错误,用于删除 C++ 中的元素
- 使用 memcpy 将动态数组的内容复制到另一个动态数组上会产生运行时错误
- 尝试将动态数组分配作为函数时出现运行时错误
- c++中动态内存分配的运行时错误