代码1 (学弟版)
#include<bits/stdc++.h>
using namespace std;
int l[15];
bool s[15]; //sad函数判断是否在同一斜线上,abs()表示绝对值
bool sad(int x,int i) { //x是当前行,i是当前行的棋子的位置
for(int j=1; j<x; j++) { //j 是之前的行 l[j] 表示在第j行的位置
if(abs(x-j)==abs(i-l[j])) return false; //如果在同一斜线上,那么行-列的绝对值 =之前的行-列的绝对值
}
return true;
}
int n,cnt;
void print() {
for (int i = 1; i <= n; ++i)
cout<<l[i]<<" ";
cout<<endl; //换行
}
inline void dfs(int x) {
// cout << x << endl; debug部分
if (x == n + 1) {
++cnt;
if (cnt <= 3)
print();
return;
}
for(int i=1; i<=n; i++) { //x是当前行,i是当前行的位置
if(s[i]||!sad(x,i)) //如果在同一斜线上,那么行-列的绝对值 =之前的行-列的绝对值
continue;
//cout<<"asdawe"<<endl; debug部分
s[i]=true;
l[x]=i;
dfs(x+1);
s[i]=false;
l[x]=0;
}
}
int main() {
cin>>n;
dfs(1);
cout<<cnt;
return 0;
}
代码2 学长版!!
#include<bits/stdc++.h>
using namespace std;
int N;
int chess[15];
bool flag[100];
int all = 0;
bool isUseful(int num,int locate) {
for(int i = 1; i<locate; i++)
if(abs(chess[i] - num) == (locate-i))
return false;
return true;
}
void print() {
for(int i = 1; i<=N; i++)
cout << chess[i] << " ";
cout << endl;
}
void dfs(int num) {
if(num==N+1) {
all++;
if(all<=3)
print();
return;
}
for(int i = 1; i<=N; i++) {
if(!flag[i] && isUseful(i,num)) {
chess[num] = i;
flag[i] = true;
dfs(num+1);
flag[i] = false;
}
}
}
int main() {
cin >> N;
dfs(1);
cout << all <<endl;
return 0;
}
代码3 王某人版
#include<cstdio>
#include<cstring>
int r[15], c[15], zd[30], cd[30],cnt;
int n;
void print(){
for (int i = 1; i <= n; ++i)
printf("%d ", r[i]);
puts("");
}
inline void dfs(int x){
if (x == n + 1){
++cnt;
if (cnt <= 3)
print();
return;
}
for (int i = 1; i <= n; ++i){
if (c[i] || zd[x - i + n + 1] || cd[i + x])
continue;
c[i] = zd[x - i + n + 1] = cd[i + x] = 1;
r[x] = i;
dfs(x + 1);
c[i] = zd[x - i + n + 1] = cd[i + x] = 0;
r[x] = 0;
}
}
int main(){
scanf("%d", &n);
dfs(1);
printf("%d", cnt);
return 0;
}
洛谷P1219 八皇后 我。。。。。。
原文:https://www.cnblogs.com/QingyuYYYYY/p/11621945.html