魔方阵定义:魔方阵是一个方阵,它的每一行、每一列和对角线之和均相等。
例如存在三阶魔方阵:
8 1 6
3 5 7
4 9 2
魔方阵中各数的排列规则:
(1)将1放在第一行中间一列。
(2)从2开始直到n*n止各数依次按照下列规则存放:每一个数存放的行比前一个数的行数减1,列数加1(例如上述的魔方阵中,6在5的上一行下一列)
(3)当上一个数的行数为1时,下一个数的行数为n,列数加1。(例如上述的魔方阵中,1在第一行,则2应该放在最后一行,列数同样加1)
(4)当上一个数的列数为n时,下一个数的行数减1,列数应该为1。(例如在上述的魔方阵中,2在第三行最后一列,则3应该放在第二行第一列)
(5)如果按照上面规则确定的位置上已经有数,或者上一个数是第一行第n列的时候,则应该把下一个数放在上一个数的下面。(例如在上述的魔方阵中,按照规定,4应该放在第1行第2列,但该位置已被1占据,所以4就放在3的下面。由于6是第1行第3列(即最后一列),故7放在6的下面)
详细代码如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[16][16],i,j,k,p,n;
p=1;
//Input a odd number that between 1 and 15.
while(p==1){
printf("Please input a odd number that between 1 and 15.");
scanf("%d",&n);
if((n!=0)&&(n<=15)&&(n%2!=0))
p=0;
}
//Initialization the matrix
for(int i=1;i<=n;i++){
for(j=1;j<=n;j++){
a[i][j]=0;
}
}
//Create the magic square
i=1;
j=n/2+1;
a[1][j]=1;
for(k=2;k<=n*n;k++){
i=i-1;
j=j+1;
if((i<1)&&(j>n)){//If the position previous number is (1,n)
i=i+2;
j=j-1;
}else{
if(i<1) //If the rows of the previous number is 1.
i=n;
if(j>n) //If the cols of the previous number is n.
j=1;
}
if(a[i][j]==0){ //If the position that we have select have no number.
a[i][j]=k;
}else{ //If the position that we have select have number.
i=i+2;
j=j-1;
a[i][j]=k;
}
}
//Print the number of the devil matrix.
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
printf("%5d",a[i][j]);
}
printf("\n");
}
return 0;
}
以上是对奇数阶的魔鬼方阵的总结,如果有不明白的地方,可以发送邮箱至[email protected]进行学习交流。