方格填数
如图,如下的10个格子,填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)一共有多少种可能的填数方案?
请填写表示方案数目的整数。
思路:我们把这样的一个区域的每一块进行命名,如下图
a b c
d e f g
h i j
我们只要保证相邻的区域的差的绝对值不等于1即可 并且数不能重复使用,代码如下
package 省赛试题2016;
public class 方格填数_填空4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a,b,c,d,e,f,g,h,i,j;
int count = 0;
for(a=0;a<=9;a++){
for(b=0;b<=9;b++){
if(Math.abs(a-b)==1||a==b) continue;
for(c=0;c<=9;c++){
if(Math.abs(c-b)==1||a==c||b==c) continue;
for(d=0;d<=9;d++){
if(Math.abs(d-a)==1||a==d||b==d||c==d) continue;
for(e=0;e<=9;e++){
if(Math.abs(e-d)==1||Math.abs(e-a)==1||Math.abs(e-b)==1||a==e||b==e||c==e||d==e) continue;
for(f=0;f<=9;f++){
if(Math.abs(f-e)==1||Math.abs(f-a)==1||Math.abs(f-b)==1||Math.abs(f-c)==1||a==f||b==f||c==f||d==f||e==f) continue;
for(g=0;g<=9;g++){
if(Math.abs(g-c)==1||Math.abs(g-f)==1||Math.abs(g-b)==1||a==g||b==g||c==g||d==g||e==g||f==g) continue;
for(h=0;h<=9;h++){
if(Math.abs(h-d)==1||Math.abs(h-e)==1||a==h||b==h||c==h||d==h||e==h||f==h||g==h) continue;
for(i=0;i<=9;i++){
if(Math.abs(i-h)==1||Math.abs(i-d)==1||Math.abs(i-e)==1||Math.abs(i-f)==1||a==i||b==i||c==i||d==i||e==i||f==i||g==i||h==i) continue;
for(j=0;j<=9;j++){
if(Math.abs(j-i)==1||Math.abs(j-f)==1||Math.abs(j-e)==1||Math.abs(j-g)==1||a==j||b==j||c==j||d==j||e==j||f==j||g==j||h==j||i==j) continue;
count++;
}
}
}
}
}
}
}
}
}
}
System.out.println(count);
}
}