该方法是将幻方盘看成是可以循环往复的,将第一个数放在第一行的中间位置,然后将下一个数字放在它的右上方,显然,该数字有可能超出幻方盘,这时候将幻方盘看成是循环往复的,比如填上1 后,在填2的时候就超出幻方盘了,这时候将幻方盘整体往上移动,这时候2会出现在1所在位置的下一列最后一行的最后,如果右上角的位置已经被占了,则将该数字放在原来数字的下面。
/*
solution for odd magic square
*/
#include<stdio.h>
#include<malloc.h>
//printf array
void display(int **arr, int length)
{
for(int i=0;i<length; ++i)
{
for(int j=0;j<length;++j)
{
printf("%-2d ",arr[i][j]);
}
printf("\n");
}
}
// fill next block
void fillNextBlock( int **arr, int *row, int *column,int length, int num)
{
int temp_row = *row-1;
int temp_column = *column+1;
if(temp_row>=length)
{
temp_row = temp_row-length;
}
else if(temp_row<0)
{
temp_row = temp_row + length;
}
if(temp_column>=length)
{
temp_column = temp_column - length;
}
else if(temp_column<0)
{
temp_column = temp_column + length;
}
if(arr[temp_row][temp_column]==0)
{
*row = temp_row;
*column = temp_column;
}
else
{
*row = *row+1;
}
arr[*row][*column]= num;
}
void magicSquare( int **arr, int length)
{
//init the first block location
int row=0;
int column = length/2;
arr[row][column] = 1;
for(int i=2;i<=(length*length); ++i)
{
fillNextBlock(arr, &row, &column, length, i);
}
}
//fill magic square block
void magicSquare(int n)
{
//positive odd
if(n<1 && (n&0x1)!=1)
return ;
int **p;
int i;
int j;
p = (int **)malloc(sizeof(int)*n);
if(p==NULL)
return ;
for( i=0;i<n;++i)
{
*(p+i)=(int *)malloc(sizeof(int)*n);
if(*(p+i)==NULL)
return ;
}
for( i=0; i<n; ++i)
{
for( j=0; j<n; ++j)
p[i][j] = 0;
}
magicSquare(p,n);
display(p,n);
//free what we malloced
for( i=0; i<n; ++i)
{
free(*(p+i));
*(p+i) = NULL;
}
free(p);
}
int main()
{
int n;
scanf("%d",&n);
magicSquare(n);
getchar();
getchar();
return 0;
}