无意间看到了关于魔幻矩阵的一篇博客,感觉挺有意思的,于是便编程分别实现了三种魔幻矩阵的c程序。
下面是关于魔幻矩阵的一篇很详细的解释说明,看代码之前,务必先去了解了解。
http://blog.youkuaiyun.com/northwolves/article/details/1796696
/*
@note 阅读代码前,请先参考以下博客中对于魔幻矩阵的算法讲解
@add http://blog.youkuaiyun.com/northwolves/article/details/1796696
@author shiyuanbo
@date 2014-03-15
**/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
typedef unsigned int uint;
/*用来存放4n阶魔幻矩阵中的4*4的小单元的结构体*/
typedef struct magic_matrix
{
uint num[4][4];
}magic_matrix_t;
/*奇数阶魔幻矩阵生成函数*/
/*
@in start 矩阵起始数字
@in odd_num 矩阵阶数2n+1
@return uint** 存放魔幻矩阵的二维动态数组
**/
/*odd_num = 2n+1*/
uint** magic_create_odd(int start,int odd_num)
{
uint **array = NULL;//存放魔幻矩阵的二维动态数组
int row = 0;//行号
int col = 0;//列号
uint data = start;//魔幻矩阵中的数字,范围为start---->start+odd_num*odd_num-1
int ret = 0;
int i = 0;
int j = 0;
/*参数校验*/
if(0 == odd_num%2)
{
printf("it is not a odd num\n");
return NULL;
}
/*为二维动态数组分配内存空间*/
array = (uint **)malloc(sizeof(uint *)*odd_num);
if(NULL == array)
{
perror("cannot alloc memory");
return NULL;
}
for(i = 0; i < odd_num; i++)
{
array[i] = (uint *)malloc(sizeof(uint)*odd_num);
if(NULL == array[i])
{
perror("cannot alloc memory");
return NULL;
}
/*初始化矩阵为全0*/
memset(array[i], 0x0, sizeof(sizeof(uint)*odd_num));
}
/*第一个数字放在第一行中间位置*/
col = odd_num/2;
array[row][col] = data;
/*依次放置魔幻矩阵其余数字*/
for(data = start+1; data < start+odd_num*odd_num; data++)