蓝桥杯 基础练习 2n皇后问题 递归

时间:2022-08-10 23:59:57

思路:

2n八皇后问题,

对于每个合法的黑色皇后排列后,计算当前条件下白皇后可以放置的种类数


#include<bits/stdc++.h>
using namespace std;
const int maxn = 10 + 7;
int n, ans = 0;
int mp[maxn][maxn];
int y1_[maxn], y2_[maxn];

bool is_ok1(int cnt, int u) {
    for(int i = 1; i <= cnt; ++i) {
        if(y1_[i] == u || abs(cnt+1-i) == abs(u-y1_[i]) ) return false;
    }
    return true;
}

bool is_ok2(int cnt, int u) {
    for(int i = 1; i <= cnt; ++i) {
        if(y2_[i] == u || abs(cnt+1-i) == abs(u-y2_[i]) ) return false;
    }
    return true;
}

int dfs2(int cnt) {
    if(cnt == n) return 1;
    int res = 0;
    for(int i = 1; i <= n; ++i) {
        if(mp[cnt+1][i] && is_ok2(cnt,i)) {
            //mp[cnt+1][i] = 0;
            y2_[cnt+1] = i;
            res += dfs2(cnt+1);
            //mp[cnt+1][i] = 1;
        }
    }
    return res;
}

int dfs1(int cnt) {
    if(cnt == n) {
            //or(int i = 1; i <= n; ++i) cout << y1_[i] << " ";
            //cout << " === " << endl;

        int res = 0;
        for(int i = 1; i <= n; ++i) {
            if(mp[1][i]) {
                mp[1][i] = 0;
                y2_[1] = i;
                res += dfs2(1);
                mp[1][i] = 1;
            }
        }
        return res;
    }
    int res = 0;
    for(int i = 1; i <= n; ++i) {
        if(mp[cnt+1][i] && is_ok1(cnt, i)) {
            mp[cnt+1][i] = 0;
            y1_[cnt+1] = i;
            res += dfs1(cnt+1);
            mp[cnt+1][i] = 1;
        }
    }
    return res;
}

int main() {
    cin >> n;
    for(int i = 1; i <= n; ++i) {
        for(int j = 1; j <= n; ++j) {
            cin >> mp[i][j];
        }
    }
    for(int i = 1; i <= n; ++i) {
        if(mp[1][i]) {
            mp[1][i] = 0;
            y1_[1] = i;
            ans += dfs1(1);
            mp[1][i] = 1;
        }
    }
    cout << ans;
    return 0;
}