Date: 2019/10/10
Degree of difficulty:Universal
Original question:P1219 八皇后
这道题用的还是dfs
只不过需要考虑几个问题
- 如何打标记
- 如何递归
1.打标记
这道题我们观察,皇后所在的行、列、左斜对角线、右斜对角线都需要打标记
左斜对角线、右斜对角线怎么打呢??
- 左斜对角线
我们发现左斜对角线上的点都满足i与j的差相等
即a[i+j]
需要打标记,但是我们发现a[i+j]
有两个相同地方,
要避免这种情况,就要加一个比较大的数,最少是n(列数)
所以为a[i-j+n]
- 右斜对角线
右斜对角线的i
和j
的和相等
所以表达式为rgtz[i+j]
2.递归
这道题需要按行输出皇后所在的列
所以我们递归的就是行数,循环的就是列数
最后输出的时候稍微注意下输出前三组就好了
AC code
#include<bits/stdc++.h>
using namespace std;
bool lez[200],rgtz[200],shu[15];
int a[17];
int cnt,n;
void dfs(int i){
if(i==n+1){
if(cnt<3){
for(int i = 1; i <= n; i++){
printf("%d ",a[i]);
}
cout<<endl;
}
cnt++;
}
for(int j = 1; j <= n; j++){
if(!shu[j] && !lez[i-j+n] && !rgtz[i+j]){
shu[j]=1;
lez[i-j+n]=1;
rgtz[i+j]=1;
a[i]=j;
dfs(i+1);
shu[j]=0;
lez[i-j+n]=0;
rgtz[i+j]=0;
a[i]=j;
}
}
}
int main() {
scanf("%d",&n);
dfs(1);
printf("%d",cnt);
return 0;
}