[USACO1.5]八皇后 Checker Challenge - 洛谷
/*
* @Description: To iterate is human, to recurse divine.
* @Autor: Recursion
* @Date: 2022-03-13 11:07:25
* @LastEditTime: 2022-03-13 19:13:23
*/
#include<iostream>
using namespace std;
const int N = 15;
int a[N];//第i行皇后方a[i]上
int cnt,n;
bool check(int x,int y)
{
for(int i=1;i<=x;i++){
if(a[i]==y) return false;
if(i+a[i]==x+y) return false;
if(i-a[i]==x-y) return false;
}
}
void dfs(int row)//第row行放何处
{
if(row==n+1){
//产生一组解
cnt++;
if(cnt<=3){
for(int i=1;i<=n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
return;
}
for(int i=1;i<=n;i++){
if(check(row,i)){
a[row]=i;
dfs(row+1);
a[row]=0;
}
}
}
int main()
{
cin>>n;
dfs(1);
cout<<cnt<<endl;
return 0;
}
/*
* @Description: To iterate is human, to recurse divine.
* @Autor: Recursion
* @Date: 2022-03-13 19:19:15
* @LastEditTime: 2022-03-13 19:54:09
*/
#include<bits/stdc++.h>
using namespace std;
int a[100],b[100],c[100],d[100];//行 列 左下到右上 左上到右下
int cnt;
int n;
void print()//输出前三个解
{
if(cnt<=3){
for(int i=1;i<=n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
}
void dfs(int i)
{
if(i==n+1){
cnt++;
print();
return;
}
for(int j=1;j<=n;j++){
if((!b[j])&&(!c[i+j])&&(!d[i-j+n])){
a[i]=j;
b[j]=1;
c[i+j]=1;
d[i-j+n]=1;
dfs(i+1);
b[j]=0;
c[i+j]=0;
d[i-j+n]=0;
}
}
}
int main()
{
cin>>n;
dfs(1);
cout<<cnt<<endl;
}