Hi I'm currently taking an introductory programming course and my final project is to write the infamous N-Queens program (find & display all possible solutions for N queens on an NxN board such that they cannot attack one another) using recursion
I feel like I at least have a slight grasp of what I'm supposd to be doing, however when I run my code, the program keeps on crashing and I don't know what the problem is; any help would be greaty appreciated
note: in my program I denote the chessboard as an array of 'n' numbers where the array index is the column # and the number itself denotes the row position of the queen,,,(also i've been running/crashing my program with N=4, as trials if that should matter)
#include <iostream>
#include <math.h>
int n;//globally defined board size
int count = 1;//# of solutions counter
void nqueen(int board[], int col, int row);
//function runs from column 0 to n (left to right), each column starting at top row 1
void nqueen(int board[], int col, int row){
if (col > n){//solution is found
std::cout<<"solution "<<count<<std::endl;
for (int i=0;i<n;i++){//display chessboard permutation of n numbers
std::cout<<board[i];
}
std::cout<<std::endl;
count += 1;//increment counter
return;
}
while (row <= n){
bool queen = true;//assume queen is placeable at row, col
if (col = 0){//first column is automatically accepted
board[col] = row;
nqueen(board, col+1, 1);
}
for (int i=0;i<col;i++){//check against previous columns
if (board[i] == row || fabs(board[i]-row) == fabs(i-col)){
queen = false;//if conflicting, can't place queen
}
}
if (queen == true){//if not conflicting, place queen and move onto next column
board[col] = row;
nqueen(board, col+1, 1);
}
if (queen == false){//conflicting, so increment row
row += 1;
}
}
nqueen(board, col-1, board[col-1]+1);//if row > n go to previous column and increment row
}
int main(){
std::cout<<"Enter integer N: ";
std::cin>>n;
std::cin.ignore();
int *board;
board = new int[n];
for (int i=0;i<n;i++){
board[i] = 0;
}
nqueen(board, 0, 1);
std::cin.get();
return 0;
}