Question:
create a 8queens solution using 1d array and the ok and print function using my current format.
Current behavior:
My code is only printing 92 solutions that use 7 queens instead of 8.
Desired behavior
I need it to print all 8 queens while keeping my current format.
Repl link:
#include <iostream>
#include <cmath>
using namespace std;
bool ok(int q[], int c){
for(int i=0;i<c;i++){
if(q[i] == q[c] || abs(q[c] - q[i]) == (c - i))
return false;
}
return true;
}
void print(int q[]) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (q[i] == j) {
cout << "Q ";
} else {
cout << ". ";
}
}
cout << endl;
}
cout << endl;
/* for(int i=0;i<8;i++){
cout << q[i];
}
cout << endl; */
}
int main() {
int board[8]={0};
int col = 0;
board[0] = 0;
int count =1;
//put the queen in the upper left square
//board[0] = 0; //b[0][0] = 1 in 2D version
while(col >= 0){
// if we backtrack beyond the first col, we are done
// if we have moved beyond the last column
if(col == 8){
cout << "Solution Number: "<< count <<endl;
print(board);
count++;
col--;
} else {
board[col]++;
// backtrack
if (board[col] > 8) {
board[col] = 0;
col--;
//if(col = -1)
// break;
// Check if the placed queen is ok else
} else if(ok(board,col)){
col++;
}
}
}
return 0;
}