为什么我的 n-queen 解决方案显示堆缓冲区溢出

问题描述 投票:0回答:1

我试过这段代码来解决n-queen问题,但是它显示了heap-buffer-overflow。我怎样才能摆脱这个问题?这个问题的 Leetcode 链接是 https://leetcode.com/problems/n-queens/。后来我编辑它在我的本地机器上运行仍然没有发现任何错误,它甚至没有显示任何输出。

#include<bits/stdc++.h>
using namespace std;

bool is_safe(vector<string> &board, int row, int col){
    int x = row, y = col, n = board.size();
    bool flag = true;
    while(x >= 0 && y < n){
        if(board[x][y] == 'Q'){
            flag = false;
            break;
        }
        x--;
        y++;
    }
    if(flag == false)return false;
    x = row, y = col;
    while(x >= 0 && y >= 0){
        if(board[x][y] == 'Q'){
            flag = false;
            break;
        }
        x--;
        y--;
    }
    if(flag == false)return false;
    x = row, y = col;
    while(x >= 0){
        if(board[x][y] == 'Q'){
            flag = false;
            break;
        }
        x--;
    }
    return flag;
}

void make_chessboard(vector<string>&board, int row, vector<vector<string>>&ans){
    if(row == board.size()){
        ans.push_back(board);
    }
    for(int j = 0; j < board[row].size(); j++){
        if(is_safe(board, row, j)){
            board[row][j] = 'Q';
            make_chessboard(board,row+1,ans);
            board[row][j] = '.';
        }
    }
}

int main(){
    int n;cin >> n;
    vector<string> board(n,string(n,'.'));
    vector<vector<string>> ans;
    make_chessboard(board, 0, ans);
    for(int i = 0; i < ans.size(); i++){
        for(int j = 0; j < ans[i].size(); j++){
            cout << ans[i][j] << endl;
        }
        cout << endl << endl;
    }
    return 0;
}

我期待得到配置正确的 nxn 棋盘

recursion backtracking n-queens
1个回答
0
投票

问题出在递归的基本情况下。你错过了一个

return
声明,你进入一个循环,使对
board[row].size()
的访问超出范围,具有未定义的行为并且可能继续递归......

所以改为:

    if(row == board.size()){
        ans.push_back(board);
        return; // <------
    }
© www.soinside.com 2019 - 2024. All rights reserved.