aoding_buxiangxuele @ 2024-08-28 16:08:10
#include<iostream>
using namespace std;
int n,cnt,ay[15],ans,c2[15];// c2列被占用
int a[100],b[100];//a表示对角线(x-y)被占用(左上到右下) b表示对角线(x+y)被占用
void dfs(int x){
if(cnt==n){
ans++;
if(ans<=3){
for(int i=1;i<=n;i++)if(ay[i])cout<<ay[i]<<' ';
cout<<endl;
}
return;
}
for(int i=x;i<=n;i++)
for(int j=1;j<=n;j++){
if(!ay[i]&&!c2[j]&&!a[n+i-j]&&!b[i+j]){
c2[j]=a[n+i-j]=b[i+j]=1;
cnt++;
ay[i]=j;//第i行的棋子在第j列
dfs(x+1);
c2[j]=a[n+i-j]=b[i+j]=0;
cnt--;
ay[i]=0;
}
}
}
int main(){
cin>>n;
dfs(1);
cout<<ans;
return 0;
}
明明自己写完和题解差不多,但是为什么就是超时呢?
by _Vistion_ @ 2024-08-29 12:17:49
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int n;
int m1[30], m2[30], m3[30], ans[15], mark=0;
void setvalue(int x, int y, int flag){
ans[x] = y;
m1[y] = flag;
m2[x+y] = flag;
m3[x-y+n] = flag;
}
void dfs(int step){
if(step>n){
mark++;
if(mark<=3){
for(int i=1; i<=n; i++){
cout<<ans[i]<<" ";
}
cout<<endl;
}
return;
}
for(int j=1; j<=n; j++){
if(m1[j] || m2[step+j] || m3[step-j+n]) continue;
setvalue(step,j,1);
dfs(step+1);
setvalue(step,j,0);
}
}
int main(){
cin>>n;
dfs(1);
cout<<mark;
return 0;
}
by aoding_buxiangxuele @ 2024-08-29 15:49:14
@YZ_zhang 找到了,是我太笨了,多写了一层行的循环,找了一天,谢谢dalao!orz
by hehe_666 @ 2024-09-06 10:01:38
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int a[55], n, k, cnt;
bool hang[55], lie[55], d1[55], d2[55];
void dfs(int step)
{
if(step > n)
{
if(cnt <= 2)
{
for(int i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
cnt++;
}
for(int i = 1; i <= n; i++)
{
int x = step, y = i;
if(hang[x] || lie[y] || d1[x - y + n] || d2[x + y]) continue;
hang[x] = lie[y] = d1[x - y + n] = d2[x + y] = true;
a[step] = i;
dfs(step + 1);
hang[x] = lie[y] = d1[x - y + n] = d2[x + y] = false;
}
}
int main()
{
cin >> n;
k = 3;
dfs(1);
cout << cnt;
return 0;
}