N Queens Problem

Posted by Abel Gancsos on Dec 14, 2011 in Blog |

//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//$$Name: n-queens.cpp $
//$$Author: Abel Gancsos $
//$$Date: 12-15-2011 $
//$$Description: Solve the n-queens problem. $
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

#include
#include
#include
using namespace std;

int count2=0;
bool attack(int i,int j,int hist[],int col); //Checks the current values
void solve(int n,int col,int hist[]); //Solves the n-queens problem
int main()
{
int n,again=1;
timeval time;
double total,start,end;

//Loop until ready to quit
while(again==1){
cout<<"Enter number of queens: ";
cin>>n;

int hist[n];

gettimeofday(&time,NULL);
start=time.tv_sec+(time.tv_usec/1000000.0); //get start time in nanoseconds
solve(n, 0, hist);

gettimeofday(&time,NULL);
end=time.tv_sec+(time.tv_usec/1000000.0); //get end time in nanoseconds
total=end-start; //calculate total time

//Print out ellapsed time
cout<<"Elapsed time: "< cout<<"1-Again 2-Close: ";
cin>>again;
}

return 0;
}

void solve(int n, int col, int hist[])
{

if (col == n) {
cout<<“\nNo. “<< ++count2< for (int i = 0; i < n; i++, putchar(‘\n’))
for (int j = 0; j < n; j++){

//if is a queen, print out “Q”, otherwise print out “.”
putchar(j == hist[i] ? ‘Q’ : ((i + j) & 1) ? ‘ ‘ : ‘.’);
}

return;
}

//continue until complete
for (int i = 0, j = 0; i < n; i++) {
for (j = 0; j < col && !attack(i, j, hist, col); j++);
if (j < col) continue;

hist[col] = i;
solve(n, col + 1, hist);
}
}

bool attack(int i, int j,int hist[], int col){

if(hist[j]==i||abs(hist[j]-i)==col-j){

return true;
}
else{
return false;
}

}

Comments are closed.

Copyright © 2012 Abe's the Word All rights reserved. Theme by Laptop Geek.