求"魔方阵"程序及算法
刚学了数组,有道习题要求打印1-n^2构成的魔方阵!如三阶魔方阵:8 1 6
3 5 7
4 9 2
我找不到他的规律!
一气之下,做了个无穷的4阶的!算很长时间!
但我想知道一个关于n阶的通用程序,要求打印出由
1-n^2构成的 所有的 魔方阵!
有人能帮帮忙么?
4阶的这个我做的!
a b c d
e f g h
i j k l
m n o p
程序如下:
main()
{
int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p;
int num=0; /* 计算4阶魔方阵有多少种 */
for(a=1;a<=16;a++)
for(b=1;b<=16;b++)
{
if (b==a) continue; /* 当取值与a相同跳出本次循环 */
for(c=1;c<=16;c++)
{
if ((c==a)||(c==b)) continue;
d=34-a-b-c;
if ((d==a)||(d==b)||(d==c)||d<1||d>16) continue;
for(e=1;e<=16;e++)
{
if ((e==a)||(e==b)||(e==c)||(e==d)) continue;
for(f=1;f<=16;f++)
{
if ((f==a)||(f==b)||(f==c)||(f==d)||(f==e)) continue;
for(g=1;g<=16;g++)
{
if ((g==a)||(g==b)||(g==c)||(g==d)||(g==e)||(g==f)) continue;
h=34-e-f-g;
if ((h==a)||(h==b)||(h==c)||(h==d)||(h==e)||(h==f)
||(h==g)||h<1||h>16) continue;
for(i=1;i<=16;i++)
{
if ((i==a)||(i==b)||(i==c)||(i==d)||(i==e)
||(i==f)||(i==g)||(i==h)) continue;
for(j=1;j<=16;j++)
{
if ((j==a)||(j==b)||(j==c)||(j==d)||(j==e)
||(j==f)||(j==g)||(j==h)||(j==i)) continue;
for(k=1;k<=16;k++)
{
if ((k==a)||(k==b)||(k==c)||(k==d)||(k==e)
||(k==f)||(k==g)||(k==h)||(k==i)||(k==j)) continue;
l=34-i-j-k;
if ((l==a)||(l==b)||(l==c)||(l==d)||(l==e)
||(l==f)||(l==g)||(l==h)||(l==i)||(l==j)
||(l==k)||l<1||l>16) continue;
m=34-a-e-i;
if ((m==a)||(m==b)||(m==c)||(m==d)||(m==e)
||(m==f)||(m==g)||(m==h)||(m==i)||(m==j)
||(m==k)||(m==l)||m<1||m>16) continue;
n=34-b-f-j;
if ((n==a)||(n==b)||(n==c)||(n==d)||(n==e)
||(n==f)||(n==g)||(n==h)||(n==i)||(n==j)
||(n==k)||(n==l)||(n==m)||m<1||m>16) continue;
o=34-c-g-k;
if ((o==a)||(o==b)||(o==c)||(o==d)||(o==e)
||(o==f)||(o==g)||(o==h)||(o==i)||(o==j)
||(o==k)||(o==l)||(o==m)||(o==n)||o<1
||o>16) continue;
p=34-d-h-l;
if ((p==a)||(p==b)||(p==c)||(p==d)||(p==e)
||(p==f)||(p==g)||(p==h)||(p==i)||(p==j)
||(p==k)||(p==l)||(p==m)||(p==n)||(p==o)
||p<1||p>16) continue;
if ((m+n+o+p)!=34) continue;
if ((a+f+k+p)!=34) continue;
if ((d+g+j+m)!=34) continue;
printf("%2d,%2d,%2d,%2d\n",a,b,c,d);
printf("%2d,%2d,%2d,%2d\n",e,f,g,h);
printf("%2d,%2d,%2d,%2d\n",i,j,k,l);
printf("%2d,%2d,%2d,%2d\n",m,n,o,p);
num++;}}}}}}}}
printf("总共有%d种排序方法!!!\n",num);
printf("\n");
}