http://acmoj.shu.edu.cn/openjudge-edu/viewproblem.php?coll_id=1&prob_id=64
分析: 深搜,约束函数的简化
代码:
//shup64 n queens
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <cmath>
using namespace std;
#define M 16
int n;
int total;
int x[M];
bool judge(int k)
{
for(int j=1;j<k;j++)
if((abs(k-j)==abs(x[k]-x[j]))||(x[j]==x[k])) return false; //不在同斜线上,不同列(j != k,即为不同行)
return true;
}
void dfs(int t)
{
if(t>n) {
total++;
if(n<=8){
cout<<"Scheme "<<total<<endl;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(j==x[i]) cout<<'q';
else cout<<'0';
}
cout<<endl;
}
//memset(x,0,sizeof(x));
}
return ;
}
for(int i=1;i<=n;i++){
x[t]=i;
if(judge(t)) dfs(t+1);
}
}
int main()
{
int cnt=1;
while(scanf("%d",&n)!=EOF){
cout<<"Case "<<cnt++<<": n="<<n<<endl;
total=0;
memset(x,0,sizeof(x));
dfs(1);
cout<<"Total: "<<total<<endl<<endl;
}
return 0;
}