### 8 Queens

Does anyone scout the problem with my Eight Queens solver?

the output is this

10000000
00000010
01000000
00000100
00000001
00100000
00001000
00010000

which is obviously wrong. so my implementation must be off

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182`` `````` #include #include "Board.h" Board::Board(){ for(int x=0; x<8; x++)//set up the empty array for(int y=0; y<8; y++) spaces[x][y]=0; } void Board:: doEightQueens(){//loop through placing queens in each possible spot. for(int x=0; x<8; x++){ if(placeQueen(*new Queen(0,x))) return; } } bool Board:: isEmpty(const int& row, const int& col) const{ return !spaces[col][row]; } bool Board:: isEmpty(const Queen& q) const{ return isEmpty(q.col, q.row); } bool Board:: placeQueen(const Queen& q){ if(q.col>=8){//if its bigger than the range we're done. return true; } else{//otherwise if(!queenSafe(q)) //if the queen is not safe return false;//head back spaces[q.col][q.row]=true;//otherwise place a queen //print(); for(int row=0; row<8; row++){//loop through the rows if(placeQueen(*new Queen(q.col+1, row)))//if it works here it works return true; } //if the for loop never solves (no return statement spaces[q.col][q.row]=false;//remove the queen we were working with return false;//go back to try again. } } bool Board:: queenSafe(const Queen& q) const{ for(int x=0; x<8; x++) for(int y=0; y<8; y++){ if(spaces[y][x]) { if(q.row==x ||q.col==y) return false; } } int dX, dY; for(int x=0; x<8; x++) for(int y=0; y<8; y++){ if(spaces[y][x]) { dX=x-q.row; dY=y-q.col; if(dX==dY) return false; } } return true; } void Board:: print(){ std::cout<<"\n"; for(int x=0; x<8; x++){ for(int y=0; y<8; y++){ if(spaces[y][x]){ std::cout<<"1"; } else std::cout<<"0"; } std::cout<<"\n"; } std::cout<<"\n"; } ``````
Last edited on
anyone?
errr... this code is scary. `if(placeQueen(*new Queen(0,x)))` is a massive memory leak.

What I would suggest doing is having a method that determines if a queen can be placed there, then place it there. Not 1 method.

Also, use cout statements to see why a queen is valid there or not etc. Start using debug so you can track the logic of the application when debugging
Topic archived. No new replies allowed.