DFS 深度有限搜索
回溯法
不知道情况一遍一遍试 ,试探性填充数据
package dayTest;
public class HuiTest {
static int count=0;
static int nums[]=new int[10];
static boolean []booleans=new boolean[10];
public static void dfs(int step){
if(step==10) {
if (nums[1] + nums[2] + nums[3] + nums[4] == nums[4] + nums[5] + nums[6] + nums[7] && nums[1] + nums[2] + nums[3] + nums[4] == nums[7] + nums[8] + nums[9] + nums[1]) {
count++;
}
return;
}
for(int i=1;i<10;i++){
if(!booleans[i]){
nums[step]=i;
booleans[i]=true;
dfs(step+1);
booleans[i]=false;
}
}
}
public static void main(String[] args) {
dfs(1);
System.out.println(count);
System.out.println(count/6);
}
}
邻里交换法
事先有数据,类似把数组分为两半,一半是确定好的数据,另一半是未确定的
第一个位置未确定,它可以和其他任何位置交换,第二个位置可以和除了第一遍交换过的位置,剩下的位置交换。
public class HuiTest {
static int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
static int count;
public static void f(int a[], int step) {
if (step == a.length - 1) {
if (a[1] + a[2] + a[3] + a[4] == a[4] + a[5] + a[6] + a[7] && a[1] + a[2] + a[3] + a[4] == a[7] + a[8] + a[9] + a[1]) {
count++;
}
return;
}
for (int i = step; i < a.length; i++) {
int temp = a[i];
a[i] = a[step];
a[step] = temp;
f(a, step + 1);
temp = a[i];
a[i] = a[step];
a[step] = temp;
}
}
public static void main(String[] args) {
f(a, 0);
System.out.println(count / 6);
}
}