ZCMU-1803: 2n皇后问题

传送

  • 八皇后问题的进阶版
  • 先枚举白皇后的位置,再枚举黑皇后的位置,判断黑皇后要多判断一下该位置是否已放置白皇后。
#include 
#include 
#include 
#include 
using namespace std;
#define INF 0x3f3f3f
#define cio ios::sync_with_stdio(false)
const int N = 100010;
const int M = 1000010;
int n;
int cnt;
int s[10][10];
int white_queen[10][10];
int black_queen[10][10];
int check(int Queen[10][10], int x, int y)
{
    // 行列
    for(int i = 1; i <= n; i++)
    {
        if(Queen[i][y]==1) return 0;
        if(Queen[x][i]==1) return 0;
    }
    // 主对角线
    for(int i = x, j = y; i > 0 && j > 0; i--, j--)
    {
        if(Queen[i][j]==1) return 0;
    }
    for(int i = x, j = y; i <= n && j <= n; i++, j++)
    {
        if(Queen[i][j]==1) return 0;
    }
    // 负对角线
    for(int i = x, j = y; i > 0 && j <= n; i--, j++)
    {
        if(Queen[i][j]==1) return 0;
    }
    for(int i = x, j = y; i <= n && j > 0; i++, j--)
    {
        if(Queen[i][j]==1) return 0;
    }
    return 1;
}

void print()
{
    cout << endl << endl;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++) cout << white_queen[i][j] << " ";
        cout << endl;
    }
    cout << endl;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++) cout << black_queen[i][j] << " ";
        cout << endl;
    }
    cout << endl << endl;
}

void find_bqueen(int x, int c)
{
    if(x>n){
        if(c==n) cnt++;
        //print();
        return;
    }
    for(int i = 1; i <= n; i++)
    {
        if(check(black_queen,x,i)==1&&s[x][i]==1&&!white_queen[x][i]){
            black_queen[x][i] = 1;
            find_bqueen(x+1,c+1);
            black_queen[x][i] = 0;
        }
    }
}

void find_wqueen(int x, int c)
{
    if(x>n){
        if(c==n) find_bqueen(1,0);
        return;
    }
    for(int i = 1; i <= n; i++)
    {
        if(check(white_queen,x,i)==1&&s[x][i]==1){
            white_queen[x][i] = 1;
            find_wqueen(x+1,c+1);
            white_queen[x][i] = 0;
        }
    }
}

int main()
{
    while(~scanf("%d", &n))
    {
        cnt = 0;
        memset(white_queen,0,sizeof(white_queen));
        memset(black_queen,0,sizeof(black_queen));
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++) scanf("%d", &s[i][j]);
        }
        find_wqueen(1,0);
        printf("%d\n", cnt);
    }
    return 0;
}

你可能感兴趣的:(题解)