奇数阶幻方求解


该方法是将幻方盘看成是可以循环往复的,将第一个数放在第一行的中间位置,然后将下一个数字放在它的右上方,显然,该数字有可能超出幻方盘,这时候将幻方盘看成是循环往复的,比如填上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;
}







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值