题目描述
把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时的所有方案数字
#include <iostream>
using namespace std;
const int N = 5, M = 17;
int sum = 34, res;
int a[N][N];
bool st[M];
bool first_check(int i){
int sum1 = 0;
for (int j = 0; j < 4; j ++ )
sum1 += a[i][j];
if (sum == sum1) return true;
return false;
}
bool check(){
//每行
for (int i = 0; i < 4; i ++ )
if (a[i][0] + a[i][1] + a[i][2] + a[i][3] != sum)
return false;
//每列
for (int j = 0; j < 4; j ++ )
if (a[0][j] + a[1][j] + a[2][j] + a[3][j] != sum)
return false;
//正对角线
if (a[0][0] + a[1][1] + a[2][2] + a[3][3] != sum) return false;
//反对角线
if (a[0][3] + a[1][2] + a[2][1] + a[3][0] != sum) return false;
return true;
}
void dfs(int u){
if (u == 16){
if (check()) res ++;
return;
}
if (u % 4 == 0){
if (!first_check(u / 4 - 1)) return;
}
for (int i = 2; i <= 16; i ++ ){
if (!st[i]){
st[i] = true;
a[u / 4][u % 4] = i;
dfs(u + 1);
st[i] = false;
}
}
}
int main(){
a[0][0] = 1;
dfs(1);
cout << res << endl;//res = 416
return 0;
}