我正在尝试使用回溯来解决 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)

本文关键字:运行时错误 动态 溢出 缓冲区 堆栈 编译 回溯 问题 queen 解决      更新时间:2023-10-16

>我正在尝试使用回溯来解决"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]在内循环中。