蓝桥杯真题 方格填数

巧妙的搜索,优雅的代码

转自

http://blog.csdn.net/weixin_38391092/article/details/79341180


如图,如下的10个格子,填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)一共有多少种可能的填数方案?
请填写表示方案数目的整数。这里写图片描述

#include<iostream>


using namespace std;

const int r=3,c=4;
int ans=0;

int map[r][c];
bool numv[15];

int fx[8]={1,-1,0,0,1,1,-1,-1};
int fy[8]={0,0,1,-1,1,-1,1,-1};

bool check(int x,int y,int num){

    int oldx,oldy; 
    for(int i=0;i<8;i++){
        oldx=x+fx[i];
        oldy=y+fy[i];
        if(oldx>=0&&oldx<r&&oldy>=0&&oldy<c){
            if(map[oldx][oldy]==num-1||map[oldx][oldy]==num+1){
                return false;
            }
        }
    }
    return true;
}

void dfs(int dep,int pos){
    if(dep==2&&pos==3){
        ans++;
        return;
    }
    if(pos>=c){
        dfs(dep+1,0);
    }
    else{
        for(int i=0;i<=9;i++){
            if(!numv[i]&&check(dep,pos,i)){         //该数字没有用过,且该格子可以使用。 
                numv[i]=true;
                map[dep][pos]=i;
                dfs(dep,pos+1);
                numv[i]=false;
                map[dep][pos]=-10;
            }
        } 
    }
}

int main(){


for(int i=0;i<r;i++){
    for(int j=0;j<c;j++){
        map[i][j]=-10;
    }
}
dfs(0,1);
cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36783389/article/details/79524553