幻方填空
幻方是把一些数字填写在方阵中,使得行、列、两条对角线的数字之和都相等。
欧洲最著名的幻方是德国数学家、画家迪勒创作的版画《忧郁》中给出的一个4阶幻方。
他把1,2,3,…16 这16个数字填写在4 x 4的方格中。
如图p1.jpg所示,即:
16 ? ? 13
? ? 11 ?
9 ? ? *
? 15 ? 1
表中有些数字已经显露出来,还有些用?和*代替。
请你计算出? 和 * 所代表的数字。并把 * 所代表的数字作为本题答案提交。
答案是一个整数,请通过浏览器直接提交该数字。
注意:不要提交解答过程,或其它辅助说明类的内容。
代码一(纯C语言)
#include<stdio.h>
#include<string.h>
void transform(int*date,int num)
{
if(num>=10)
{
int r1 = 16+date[0]+date[1]+13;
int r2 = date[2]+date[3]+11+date[4];
int r3 = 9+date[5]+date[6]+date[7];
int r4 = date[8]+15+date[9]+1;
int c1 = 16+date[2]+9+date[8];
int c2 = date[0]+date[3]+date[5]+15;
int c3 = date[1]+11+date[6]+date[9];
int c4 = 13+date[4]+date[7]+1;
int l1 = 16+date[3]+date[6]+1;
int l2 = 13+11+date[5]+date[8];
if(r1==r2&&r2==r3&&r3==r4&&c1==c2&&c2==c3&&c3==c4&&c4==l1&&l1==l2)
printf("%d",date[7]);
return;
}//条件判断
for(int i = num;date[i];i++){
int t = date[i];
for(int j=i-1;j>=num;j--) date[j+1] = date[j];
date[num] = t;
transform(date,num + 1);
t = date[num];
for(int j = num;j < i;j ++) date[j] = date[j+1];
date[i] = t;
}//字典序全排列-升序
}
int main()
{
int date[10]={2,3,4,5,6,7,8,10,12,14};
transform(date,0);
return 0;
}
代码二(c++函数库中的next_permutation()函数)
#include<stdio.h>
#include<algorithm>
using namespace std;
int date[10]={2,3,4,5,6,7,8,10,12,14};
void check(int*date)
{
int r1 = 16+date[0]+date[1]+13;
int r2 = date[2]+date[3]+11+date[4];
int r3 = 9+date[5]+date[6]+date[7];
int r4 = date[8]+15+date[9]+1;
int c1 = 16+date[2]+9+date[8];
int c2 = date[0]+date[3]+date[5]+15;
int c3 = date[1]+11+date[6]+date[9];
int c4 = 13+date[4]+date[7]+1;
int l1 = 16+date[3]+date[6]+1;
int l2 = 13+11+date[5]+date[8];
if(r1==r2&&r2==r3&&r3==r4&&c1==c2&&c2==c3&&c3==c4&&c4==l1&&l1==l2)
printf("%d",date[7]);
return;
}
int main()
{
do{
check(date);//条件判断
}while(next_permutation(date,date+11));
return 0;
}
这个题不要选择去用字符型数组,因为到条件判断会很麻烦,会导致你感觉逻辑没问题,却不输出结果。这是因为如果用字符型数组,会导致判断时采用ASC码,从而导致找不到结果。
不过如果你把字符型数组的每一位都转化成整型,应该可行(但挺麻烦的),例如下面这串代码的转换:
#include<stdio.h>
int main()
{
char a = '4';
int c = a - '0';
printf("%d",a);//此时输出的是4的ASC值52,说明是字符
printf("%d",c);//此时输出整型4,说明是整型
printf("%c",c);//此处输出4代表的ASCii值为4的字符,说明是整型
return 0;
}
(不过好像只有字符0~9有对应的ASCii值(个人感觉),对于像字符’12’这类的我也不知道怎么转)