题目描述
点击查看原题
思路描述
- 因为有n个皇后,n*n个格子,所以每行都会有一个皇后,所以用一维数组st存储每位皇后所在的列(st下标表示第几位皇后,也就是行数)
- 在正对角线上时,行列相减相等,在负对角线时,行列相加相等
- 确定每个皇后所在的列,通过查看该位皇后与前一皇后所在列是否冲突确定
代码
#include<stdio.h>
#include<math.h>
int n;
int res;//符合条件的结果数
int st[20];
int check(int r,int c){
int i;
int t1,t2,t3,t4;
for(i=1;i<r;i++){//看当前行的皇后位置与前一行是否冲突
t1=st[i]+i;//第i个皇后的行列之和相加
t2=st[i]-i;
t3=r+c;
t4=c-r;
if(c==st[i] || (t1==t3 && abs(i-r)<3) || (t2==t4 && abs(i-r)<3))return 0;
}
return 1;
}
void dfs(int h){
int i;
if(h>n){
res++;
return;
}
for(i=1;i<=n;i++){//遍历列
if(check(h,i)){
st[h]=i;
dfs(h+1);
}
}
}
int main(){
scanf("%d",&n);
dfs(1);
printf("%d",res);
return 0;
}