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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include<iostream>
#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
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