one dimensional 8 queens problem
Oct 7, 2010 at 2:52am UTC
Hi I am working on 8 queen problem using a one dimension without backtrack.
my programs prints a infinte loops and none of them are real solutions.
can someone edit my code?
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
#include<cmath>
#include<iostream>
using namespace std;
bool ok ( int b[],int c )
{
for ( int i=0; i<8; i++)
if ( b[i]==b[8]||( abs (b[8]-b[i])==8-i)) return false ;
return true ;
}
void print ( int a[], int counter) {
cout <<"solution #" << counter << ":" << endl;
for ( int r=0; r<8; r++ ) {
for ( int c=0; c<8; c++) {
if ( a[c]==r) cout << 1<< " " ;
else cout << 0 << " " ;
}
cout << endl;
}
cout << endl;
}
int main( ){
int board[8],c=0;c++;
int count= 0;
for (int i0 =0; i0 <8; i0 ++)
for (int i1 =0; i1 <8; i1 ++)
for (int i2 =0; i2 <8; i2 ++)
for (int i3 =0; i3 <8; i3 ++)
for (int i4 =0; i4 <8; i4 ++)
for (int i5 =0; i5 <8; i5 ++)
for (int i6 =0; i6 <8; i6 ++)
for (int i7 =0; i7 <8 ; i7 ++){
board[0]=i0;
board[1]=i1;
board[2]=i2;
board[3]=i3;
board[4]=i4;
board[5]=i5;
board[6]=i6;
board[7]=i7;
if (ok(board,c)) print(board, ++count);
for ( int r=0;r<8; r++ ) board[r]=0;
}
return 0;
}
Last edited on Oct 7, 2010 at 2:57am UTC
Oct 7, 2010 at 3:13am UTC
if ( b[i]==b[8]||( abs (b[8]-b[i])==8-i))
crash b[8]
it's out of bounds.
Last edited on Oct 7, 2010 at 3:23am UTC
Oct 7, 2010 at 3:34am UTC
I edited the b[8] to b[c], but it still print infinite loops. help please
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
#include<cmath>
#include<iostream>
using namespace std;
bool ok ( int b[],int c )
{
for ( int i=0; i<c; i++)
if ( b[i]==b[c]||( abs (b[c]-b[i])==c-i)) return false ;
return true ;
}
void print ( int a[], int counter) {
cout <<"solution #" << counter << ":" << endl;
for ( int r=0; r<8; r++ ) {
for ( int c=0; c<8; c++) {
if ( a[c]==r) cout << 1<< " " ;
else cout << 0 << " " ;
}
cout << endl;
}
cout << endl;
}
int main( ){
int board[8],c=0;c++;
int count= 0;
for (int i0 =0; i0 <8; i0 ++)
for (int i1 =0; i1 <8; i1 ++)
for (int i2 =0; i2 <8; i2 ++)
for (int i3 =0; i3 <8; i3 ++)
for (int i4 =0; i4 <8; i4 ++)
for (int i5 =0; i5 <8; i5 ++)
for (int i6 =0; i6 <8; i6 ++)
for (int i7 =0; i7 <8 ; i7 ++){
board[0]=i0;
board[1]=i1;
board[2]=i2;
board[3]=i3;
board[4]=i4;
board[5]=i5;
board[6]=i6;
board[7]=i7;
if (ok(board,c)) print(board, ++count);
for ( int r=0;r<8; r++ ) board[r]=0;
}
return 0;
}
Oct 7, 2010 at 3:56am UTC
So you just change b[8] to b[1] (very likely to return true)
What you mean with "print infinite loops"?
Topic archived. No new replies allowed.