问题如下:
方格填数
如下的10个格子
+--+--+--+
| | | |
+--+--+--+--+
| | | | |
+--+--+--+--+
| | | |
+--+--+--+
(如果显示有问题,也可以参看【图1.jpg】)
填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)
一共有多少种可能的填数方案?
请填写表示方案数目的整数。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。
思路:菜鸡一枚,用了十重for循环+各种if判断出的答案,不过思路简单,而且写起来不费劲(不喜勿喷)
代码如下:
import java.util.HashMap;
import java.util.Scanner;
public class Main
{ static int count=0;
public static void main(String[] args)
{
for(int a=0;a<=9;a++) {
for(int b=0;b<=9;b++) {
if(b!=a&&Math.abs(b-a)!=1)
for(int c=0;c<=9;c++) {
if(c!=a&&c!=b&&Math.abs(c-b)!=1)
for(int d=0;d<=9;d++) {
if(d!=a&&d!=b&&d!=c&&Math.abs(d-a)!=1&&Math.abs(d-b)!=1)
for(int e=0;e<=9;e++) {
if(e!=a&&e!=b&&e!=c&&e!=d&&Math.abs(e-d)!=1&&Math.abs(e-a)!=1&&Math.abs(e-b)!=1&&Math.abs(e-c)!=1)
for(int f=0;f<=9;f++) {
if(f!=a&&f!=b&&f!=c&&f!=d&&f!=e&&Math.abs(f-e)!=1&&Math.abs(f-b)!=1&&Math.abs(f-c)!=1)
for(int g=0;g<=9;g++) {
if(g!=a&&g!=b&&g!=c&&g!=d&&g!=e&&g!=f&&Math.abs(g-c)!=1&&Math.abs(g-f)!=1)
for(int h=0;h<=9;h++) {
if(h!=a&&h!=b&&h!=c&&h!=d&&h!=e&&h!=f&&h!=g&&Math.abs(h-d)!=1&&Math.abs(h-e)!=1&&Math.abs(h-f)!=1)
for(int i=0;i<=9;i++) {
if(i!=a&&i!=b&&i!=c&&i!=d&&i!=e&&i!=f&&i!=g&&i!=h&&Math.abs(i-e)!=1&&Math.abs(i-f)!=1&&Math.abs(i-g)!=1&&Math.abs(i-h)!=1)
for(int j=0;j<=9;j++) {
if(j!=a&&j!=b&&j!=c&&j!=d&&j!=e&&j!=f&&j!=g&&j!=h&&j!=i&&Math.abs(j-f)!=1&&Math.abs(j-g)!=1&&Math.abs(j-i)!=1) {
System.out.println(" "+h+" "+i+" "+j);
System.out.println(d+" "+e+" "+f+" "+g);
System.out.println(a+" "+b+" "+c);
System.out.println();
count++;
}
}
}
}
}
}
}
}
}
}
}
System.out.println(count);
}
}