My 8queens solution code not working

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

:wave: Welcome to the forums, @Hahsebuljoy!

It seems that this post is asking for answers to a school assignment. It is against Replit Ask policy for community members to request or post complete answers to homework-like questions. On the other hand, the community can assist you in working through and understanding the core fundamentals of computer programming to help you figure out your question by yourself, though.

1 Like