hdu 2553 N皇后问题(DFS)

Problem - 2553 (hdu.edu.cn)(N <= 10)

复制代码
#include<iostream>
#include<cstring>
using namespace std;
int n,tot=0;
int col[12];
bool check(int c,int r){
    for(int i=0;i<r;i++){
        if(col[i]==c || (abs(col[i]-c)==abs(i-r))) return false;
    }
    return true;
}
void DFS(int r){
    if(r==n){
        tot++;
        return ;
    }
    for(int c=0;c<n;c++){
        if(check(c,r)){
            col[r]=c;
            DFS(r+1);
        }
    }
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int ans[12]={0};
    for(n=0;n<=10;n++){
        memset(col,0,sizeof(col));
        tot=0;
        DFS(0);
        ans[n]=tot;
    }
    while(cin>>n){
        if(!n) return 0;
        cout<<ans[n]<<endl;
    }
    return 0;
}
复制代码

 P1219 [USACO1.5] 八皇后 Checker Challenge - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) (6 <= N <= 13)

复制代码
#include<iostream>
using namespace std;
int n,m1[30],m2[30],m3[30],ans[15],res=0;
void setvalue(int step,int j,int k){
    ans[step]=j;
    m1[j]=k;
    m2[j+step]=k;
    m3[step-j+n]=k;
}
void dfs(int step){
    if(step>n){
        res++;
        if(res<=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);
    }
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>n;
    dfs(1);
    cout<<res<<endl;
    
    return 0;
}
复制代码

 

posted @   ACCbulb  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示