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