四阶幻方
题目描述
把1~16的数字填入4x4的方格中,使得行、列以及两个对角线的和都相等,满足这样的特征时称为:四阶幻方。
四阶幻方可能有很多方案。如果固定左上角为1,请计算一共有多少种方案。
比如:
1 2 15 16
12 14 3 5
13 7 10 4
8 11 6 9
以及:
1 12 13 8
2 14 7 11
15 3 10 6
16 5 4 9
就可以算为两种不同的方案。
输出
请提交左上角固定为1时的所有方案数字
package oj;
import java.util.Scanner;
public class Main {
static int[] arr = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
static int[] vis = new int[16];
static int[] res = new int[16];
static int cnt = 0;
static int s;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// res[0] = 1;
// vis[0] = 1;
// dps(1);
System.out.println(416);
}
static void dps(int i) {
if(i%4==0) { //剪枝
if(!test2(res,i))
return;
}
if(i==16) {
if(test(res)) {
cnt++;
}
}else {
for(int j = 1; j < 16; j++) {
if(vis[j]==0) {
vis[j] = 1;
res[i] = arr[j];
dps(i+1);
vis[j] = 0;
}
}
}
}
static boolean test(int[] res) {
int t = 0, s2 = s;
//对角线
s = res[0]+res[5]+res[10]+res[15];
s2 = res[3]+res[6]+res[9]+res[12];
if(s!=s2)
return false;
//行
for(int i = 0; i < 4; i++) {
s2 = 0;
for(int j = t; j < t+4; j++) {
s2 += res[j];
}
t+=4;
if(s!=s2)
return false;
}
//列
t = 0;
for(int i = 0; i < 4; i++) {
s2 = 0;
for(int j = t; j <= t+12; j+=4) {
s2 += res[j];
}
t++;
if(s!=s2)
return false;
}
return true;
}
static boolean test2(int[] res,int i) {
int s1 = 0;
for(int j = i-4; j < i; j++) {
s1 += res[j];
}
return s1==34;
}
}
(1+2+3+4+5+…+16)/4 = 34
dfs+剪枝
2021-01-23