12求助

P1219 [USACO1.5] 八皇后 Checker Challenge

kevin4 @ 2023-09-23 14:49:26

#include<bits/stdc++.h>
using namespace std;
int n,a[14],tot;
int dfs(int steps) {
    if(steps==n+1) {
        if(++tot<=3) {
            for(int i=1; i<=n; i++)cout<<a[i]<<" ";
            cout<<endl;
        }
        return 1;
    }
    int ans=0;
    for(int i=1; i<=n; i++) {
        bool flag=0;
        for(int j=1; j<=n; j++) {
            if(j<=steps) {
                if(a[steps-j]==i||a[steps-j]==i-j||a[steps-j]==i+j) {
                    flag=1;
                    break;
                }
            }
        }
        if(flag)continue;
        a[steps]=i;
        ans+=dfs(steps+1);
        a[steps]=0;
    }
    return ans;
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    cout<<dfs(1);
    return 0;
}

|