2016蓝桥杯省赛C/C++A组第三题 方格填数

时间:2022-03-13 06:12:14

题意:如下的10个格子 
2016蓝桥杯省赛C/C++A组第三题 方格填数 
填入0~9的数字。要求:连续的两个数字不能相邻。 (左右、上下、对角都算相邻) 
一共有多少种可能的填数方案? 

分析:dfs,划定边界,行1~4,列1~3,初始化为INT_INF,这样所填入的数字与INT_INF一定不相邻,所以可不必单独考虑(1,1)和(3,4)两个格子。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
    if(fabs(a - b) < eps) return 0;
    return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 10000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int a[5][5];
int vis[10];
bool judge(int x, int y){
    return x >= 1 && x <= 3 && y >= 1 && y <= 4;
}
bool deal(int x, int y, int v){
    for(int i = 0; i < 8; ++i){
        int tmpx = x + dr[i];
        int tmpy = y + dc[i];
        if(judge(tmpx, tmpy)){
            if(abs(a[tmpx][tmpy] - v) == 1) return false;
        }
    }
    return true;
}
int ans;
void dfs(int x, int y){
    if(x == 3 && y == 4){
        ++ans;
        return;
    }
    for(int i = 0; i <= 9; ++i){
        if(!vis[i] && deal(x, y, i)){
            vis[i] = 1;
            a[x][y] = i;
            if(y < 4){
                dfs(x, y + 1);
            }
            else{
                dfs(x + 1, 1);
            }
            vis[i] = 0;
            a[x][y] = INT_INF;
        }

    }
}
int main(){
    memset(a, INT_INF, sizeof a);
    dfs(1, 2);
    printf("%d\n", ans);
    return 0;
}