思路
同一排同一列和斜45度不能放
也就是米字上没有其他皇后
如果米字范围内有其他皇后则跳过
再搜索
代码
#include<bits/stdc++.h>
using namespace std;
int ans;
int n;
char s[15][15];
int dir[4][2]={{-1,1},{1,-1},{-1,-1},{1,1}}; //四个方向
void init(int n){ //数组初始化
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++){
s[i][j]='.';
}
}
}
bool check(int x,int y){ //检查函数
for(int i=0;i<y;i++){ //检查列
if(s[x][i]=='Q')
return false;
}
for(int i=0;i<x;i++){ //检查行
if(s[i][y]=='Q')
return false;
}
for(int i=0;i<4;i++){ //检查四个方向
int tx=x;
int ty=y;
while(tx>=0&&ty>=0&&tx<n&&ty<n){ //保证没有超出棋盘
if(s[tx][ty]=='Q'){
return false;
}
tx+=dir[i][0];
ty+=dir[i][1];
}
}
return true;
}
void dfs(int cow){
if(cow==n){
ans++;
return;
}
for(int i=0;i<n;i++){
if(check(cow,i)){
s[cow][i]='Q';
dfs(cow+1);
s[cow][i]='.';//回溯,把'Q' 变回'.'
}
}
}
int main()
{
while(cin>>n){
int a[15];
for(int i=0;i<11;i++)
{
init(n);
ans=0;
dfs(0);
a[i]=ans;
}
cout<<a[n]<<endl;
}
return 0;
}