寒假Day58:蓝桥杯-2n皇后问题-八皇后变形

题目链接:

http://oj.ecustacm.cn/problem.php?id=1404

思路:

经典八皇后变形问题

标记行、判断列和两条对角线即可

先下黑皇后,下完后再去下白皇后

注意:这一题是1可以放,0不可以放

判断方式:

int check(int *queen,int x)//判断列和两条对角线
{
    for(int i=1; i<x; i++)
    {
        int w=queen[i]-queen[x];
        if(w==0||w==i-x||w==x-i)
            return 0;
    }
    return 1;
}

如何下黑皇后:

int black(int x)
{
    if(x==n+1)
        white(1);
    else
    {
        for(int i=1; i<=n; i++)
        {
            if(a[x][i]==1)
            {
                hei[x]=i;
                if(check(hei,x))
                    black(x+1);//递归下一行
            }
        }
    }
}

下白皇后的时候需要注意下不要和黑皇后重复了:

if(a[x][i]==1&&i!=hei[x])

AC代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 
 5 int a[10][10],hei[10],bai[10],ans,n;
 6 
 7 int check(int *queen,int x)//判断列和两条对角线
 8 {
 9     for(int i=1; i<x; i++)
10     {
11         int w=queen[i]-queen[x];
12         if(w==0||w==i-x||w==x-i)
13             return 0;
14     }
15     return 1;
16 }
17 
18 void white(int x)
19 {
20     if(x==n+1)
21     {
22         ans++;
23         return;
24     }
25     for(int i=1; i<=n; i++)
26     {
27         if(a[x][i]==1&&i!=hei[x])
28         {
29             bai[x]=i;//在(x,i)放白皇后
30             if(check(bai,x))
31                 white(x+1);
32         }
33     }
34 }
35 
36 int black(int x)
37 {
38     if(x==n+1)
39         white(1);
40     else
41     {
42         for(int i=1; i<=n; i++)
43         {
44             if(a[x][i]==1)
45             {
46                 hei[x]=i;
47                 if(check(hei,x))
48                     black(x+1);//递归下一行
49             }
50         }
51     }
52 }
53 
54 int main()
55 {
56     cin>>n;
57     ans=0;
58     for(int i=1; i<=n; i++)
59     {
60         for(int j=1; j<=n; j++)
61             cin>>a[i][j];
62     }
63     black(1);//第一行
64     cout<<ans<<endl;
65     return 0;
66 }
View Code

猜你喜欢

转载自www.cnblogs.com/OFSHK/p/12547048.html
今日推荐