-1

I tried this code to solve the n-queen problem, but it shows heap-buffer-overflow. How can I get rid of this problem? The Leetcode link for this problem is https://leetcode.com/problems/n-queens/. Later I edited it to run on my local machine still not finding any bugs, there it wasn't even showing any output.

#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;
}

I was expecting to get nxn chess-board with correct configuration

Evg
  • 25,259
  • 5
  • 41
  • 83
  • Sorry if you are struggling to solve this problem. Actually, I just found out that I forgot to add a return statement on the make_chessboard function that's why it was showing buffer overflow now it's working fine – dexter 247 Feb 27 '23 at 14:10
  • Don't waste your time on scam coding websites. You're not learning proper C++ there, but some garbage written by poorly educated people who are not competent to teach programming. [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) | [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Evg Feb 28 '23 at 03:20

1 Answers1

0

The problem is in the base case of your recursion. You're missing a return statement whereby you get into a loop that makes an out of range access to board[row].size() with undefined behaviour and possibly recursion continuing...

So change to:

    if(row == board.size()){
        ans.push_back(board);
        return; // <------
    }
trincot
  • 317,000
  • 35
  • 244
  • 286