转载请注明出处:http://www.cnblogs.com/zhishoumuguinian/p/8395458.html
把1~16的数字填入4x4的方格中,使得行、列以及两个对角线的和都相等,满足这样的特征时称为:四阶幻方。四阶幻方可能有很多方案。如果固定左上角为1,请计算一共有多少种方案。
比如: 以及:
1 2 15 16 1 12 13 8
12 14 3 5 2 14 7 11
13 7 10 4 15 3 10 6
8 11 6 9 16 5 4 9
就可以算为两种不同的方案。请提交左上角固定为1时的所有方案数字,不要填写任何多余内容或说明文字。
答案:416
1 #include <iostream> 2 #include <fstream> 3 #include <iomanip> 4 using namespace std; 5 int a[5][5]; 6 int flag[20]={0}; 7 int ans=0; 8 bool Check(int x, int y) 9 { 10 if(x<3) 11 { 12 if(y<3) return true; 13 if(a[x][0]+a[x][1]+a[x][2]+a[x][3]==34) 14 return true; 15 return false; 16 } 17 else 18 { 19 if(y==0) 20 if((a[0][0]+a[1][0]+a[2][0]+a[3][0]!=34)||(a[0][3]+a[1][2]+a[2][1]+a[3][0]!=34)) return false; 21 if(y==1||y==2) 22 if(a[0][y]+a[1][y]+a[2][y]+a[3][y]!=34) return false; 23 if(y==3) 24 if((a[0][y]+a[1][y]+a[2][y]+a[3][y]!=34)||(a[0][0]+a[1][1]+a[2][2]+a[3][3])!=34) return false; 25 return true; 26 } 27 } 28 29 30 void dfs(int x, int y) 31 { 32 if(x==4) 33 { 34 ans++; 35 return; 36 } 37 for(int num=1; num<=16; num++) 38 { 39 if(flag[num]==0) 40 { 41 a[x][y]=num; 42 flag[num]=1; 43 if(Check(x,y)) 44 { 45 if(y<3) dfs(x,y+1); 46 else dfs(x+1,0); 47 } 48 flag[num]=0; 49 } 50 } 51 52 53 } 54 55 int main() 56 { 57 flag[1]=1; 58 a[0][0]=1; 59 dfs(0,1); 60 cout<<ans; 61 62 return 0; 63 }
闲的把所有四阶幻方都打印出来了,感兴趣可以看一下《四阶幻方所有可能穷举》。