如图,如下的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;
}
2018/03/30
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int ans=0;
int a[3][4];
int num[10];
int fx[]={-1,-1,0,1,1,1,0,-1};
int fy[]={0,1,1,1,0,-1,-1,-1};
bool check(int x,int y,int i){
int newx;
int newy;
for(int k=0;k<8;k++){
newx=x+fx[k];
newy=y+fy[k];
if(newx>=0&&newx<3&&newy>=0&&newy<4){
if(abs(a[newx][newy]-i)==1)
return false;
}
}
return true;
}
void dfs(int x,int y){
if(x==2&&y==3){
ans++;
return ;
}
for(int i=0;i<10;i++){
if(!num[i]&&check(x,y,i)){
a[x][y]=i;
num[i]=1;
if(y==3)
dfs(x+1,0);
else dfs(x,y+1);
num[i]=0;
a[x][y]=-10;
}
}
}
int main(){
a[0][0]=a[2][3]=-10;
//全部初始化为-10,这个很important,如果不这么做,运行出来的结果就只
//有1579.
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
a[i][j]=-10;
}
}
dfs(0,1);
cout<<ans<<endl;
return 0;
}
PS:这道题最初忘记把全部方格初始化为默认值-10,然后程序跑起来后一直只有1579,和答案1580就差1,后来发现bug出现在一开始没有初始化为默认值-10了。