八皇后

#include <fstream>
#include
<cmath>
#define MAX 8
using namespace std;

ofstream cout(
"out");

int queens[MAX];
int sum=0;

void print();
void placequeens(int i);
bool isValid(int n);

void print(){
for (int i=0;i<MAX;i++){
for (int j=0;j<MAX;j++){
if(j==queens[i])
cout
<<"Q ";
else
cout
<<". ";
}
cout
<<endl;
}
}

void placequeens(int i){
for (int j=0;j<MAX;j++){
if(i==MAX){
sum
++;
cout
<<"# "<<sum<<endl;
print();
return;
}
queens[i]
=j;
if(isValid(i)) placequeens(i+1);
}
}

bool isValid(int n){
for (int i=0;i<n;i++){
if(queens[i]==queens[n]) return false;
if(abs(queens[i]-queens[n])==(n-i)) return false;
}
return true;
}

int main()
{
placequeens(
0);
cout
<<"total "<<sum<<"."<<endl;
return 0;
}

posted @ 2011-04-21 00:35  wwwwwwwww11we  阅读(171)  评论(0编辑  收藏  举报