hdu 2553 N皇后问题(DFS模板)

accbulb / 2024-02-06 / 原文

Problem - 2553 (hdu.edu.cn)

#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;
}