题目描述
方格填数
思路分析
全排列+检查
代码实现
package com.atguigu.TEST;import static java.lang.Math.abs;class Main{static int a[]={0,1,2,3,4,5,6,7,8,9};static int ans;public static boolean check(){if (abs(a[0] - a[1]) == 1 || abs(a[0] - a[3]) == 1 || abs(a[0] - a[4]) == 1 || abs(a[0] - a[5]) == 1 ||abs(a[1] - a[2]) == 1 || abs(a[1] - a[4]) == 1 || abs(a[1] - a[5]) == 1 || abs(a[1] - a[6]) == 1 ||abs(a[2] - a[5]) == 1 || abs(a[2] - a[6]) == 1 ||abs(a[3] - a[4]) == 1 || abs(a[3] - a[7]) == 1 || abs(a[3] - a[8]) == 1 ||abs(a[4] - a[5]) == 1 || abs(a[4] - a[7]) == 1 || abs(a[4] - a[8]) == 1 || abs(a[4] - a[9]) == 1 ||abs(a[5] - a[6]) == 1 || abs(a[5] - a[8]) == 1 || abs(a[5] - a[9]) == 1 ||abs(a[6] - a[9]) == 1 ||abs(a[7] - a[8]) == 1 ||abs(a[8] - a[9]) == 1)return false;return true;}public static void f(int k){if(k==10){//一种排列已经生成if(check())ans++;return;}//从k往后每个数字都可以放在k位for (int i = k; i < 10; i++) {int temp=a[i];a[i]=a[k];a[k]=temp;f(k+1);temp=a[i];a[i]=a[k];a[k]=temp;}}public static void main(String[] args) {f(0);System.out.println(ans);}
}
答案
1580