第七届蓝桥杯省赛6:方格填数


方格填数

如下的10个格子
+--+--+--+
| | | |
+--+--+--+--+
| | | | |
+--+--+--+--+
| | | |
+--+--+--+

(如果显示有问题,也可以参看【图1.jpg】)

填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)

一共有多少种可能的填数方案?

请填写表示方案数目的整数。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。

图1.jpg

next_permutation很好用

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[12]={-2,0,1,2,3,4,5,6,7,8,9,-2};
int dx[8]={1,1,1,0,-1,-1,-1,0};
int dy[8]={-1,0,1,1,1,0,-1,-1};
int res;
bool judge()
{
    for(int i=1;i<=10;i++)
    {
        int y=i/4;
        int x=i%4;
        for(int k=0;k<8;k++)
        {
            int ny=y+dy[k];
            int nx=x+dx[k];
            int j=ny*4+nx;
            if(0<=ny&&ny<3&&0<=nx&&nx<4)
            {    
                if(abs(a[j]-a[i])==1)
                    return false;
            }
        }
    }
    return true;
}
int main()
{
    do{
        if(judge())
            res++;
    }while(next_permutation(a+1,a+11));
    
    printf("%d
",res);
    
    return 0;
}
/*
res:1580
*/
原文地址:https://www.cnblogs.com/program-ccc/p/5321306.html