蓝桥杯真题 方格填数

巧妙的搜索,优雅的代码

转自

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值