Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Breadth-first Eight Queens Problem

Status
Not open for further replies.

brodie23

Programmer
Jul 15, 2003
1
US
Hi, I've done this depth-firs, but now doing it breadth-first is giving me some trouble. I'm pretty sure I'm queueing up right, etc... But, I think the checkvalid function is off a little. Can somebody give some suggestions? Thanks. Code:
#include <queue>
#include <iostream>
#include <math.h>

using namespace std;

#define N 8

int x = 0;
bool ask = true;

bool checkvalid(int);

typedef struct
{
int a[N + 1];
} array;

array a = {0};
array b = {0};

queue<array> q;

void main()
{
int sizeQ;
int i, num;

for(i = 1, num = 1; num <= N; ++num)
{
a.a = num;
q.push(a);
}

sizeQ = q.size();

cout << &quot;Size of queue is: &quot; << sizeQ << endl;

sizeQ = q.size();
/*
for(int j = 1; j <= N; ++j)
{
for(i = 1; i <= N; ++i)
{
cout << q.front().a;

}
cout << endl;
q.pop();
}
*/
// iterate through queue, pushing
// valid combinations, and poping
// all previous partial solutions

while(q.front().a[8] != N)
{
// loop to check every possible combination
// between 1 and N for the next board

for(i = 1; i <= N; ++i)
{
// if move is valid push the new
// legal combination onto the queue

if(checkvalid(i++))
{
q.push(b);
}

}
q.pop();
}

for(i = 1; i <= sizeQ; ++i)
{
cout << i << &quot;. &quot; << &quot;Q[1..8] = &quot;;

for(int j = 1; j <= N; ++j)
{
cout << q.front().a << &quot; &quot;;
}

cout << endl;
q.pop();
}

}

bool checkvalid(int x)
{
int i;

bool flag = true;

// initalize the new array 'b'
// to be used to push onto the
// queue, when a good placement
// has been found

for(i = 1; i <= N; ++i)
{
b.a = q.front().a;
}

// check for a valid move

for(i = 1; i <= N; ++i)
{
if(b.a[x] == b.a)
{
flag = false;
}
if((x - i) == (abs(b.a[x] - b.a)))
{
flag = false;
}
if(flag)
{
b.a[x] = x;
}

}




return flag;
}
 
>> is giving me some trouble

A description of the &quot;trouble&quot; would be helpful. Error messages... whatever.

-pete
 
Try reposting with the Process TGML checkbox (below) unchecked.

In order to test for legality, you must examine all vertical, horizontal, and diagonal lines of attack at a given square. I'm not clear that your &quot;checkvalid()&quot; does so.

Solving the problem would be simpler if you approximated a chess board with an 8 by 8 double-scripted array.

It also increases your chance of success if you keep track of which queen placements attack the fewest number of unattacked squares.

I have a little source to get you started if you'd like.

Hope all of that's helpful! :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top