版权声明:本文为博主原创文章,未经博主允许不得转载,欢迎添加友链。 https://blog.csdn.net/qq_42835910/article/details/88691435
如下的10个格子
(如果显示有问题,也可以参看【图1.jpg】)
填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)
一共有多少种可能的填数方案?
请填写表示方案数目的整数。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。ans: 1580
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int a[105], cell[9][9];
const int dx[8] = {0,-1,-1,-1,0,1,1,1}, dy[8] = {1,1,0,-1,-1,-1,0,1};
bool check(int x,int y){
int a = cell[x][y];
for(int i = 0; i < 8; i++)
if( abs(a - cell[x+dx[i]][y+dy[i]]) == 1) return false;
return true;
}
bool ok(){
for(int i = 2; i <= 4; i++)
if(!check(1,i)) return false;
for(int i = 1; i <= 4; i++)
if(!check(2,i)) return false;
for(int i = 1; i <= 3; i++)
if(!check(3,i)) return false;
return true;
}
int main(int argc, char** argv) {
for(int i = 0; i < 10; i++)
a[i] = i;
for(int i = 0; i <= 9; i++)
for(int j = 0; j <= 9; j++)
cell[i][j] = 99;
int ans = 0;
do{
int len = 0;
for(int i = 2; i <= 4; i++) cell[1][i] = a[len++];
for(int i = 1; i <= 4; i++) cell[2][i] = a[len++];
for(int i = 1; i <= 3; i++) cell[3][i] = a[len++];
if( ok()) ans++;
}while(next_permutation(a, a+10));
cout<< ans <<endl;
return 0;
}