魔幻矩阵全解(有全部代码说明)

无意间看到了关于魔幻矩阵的一篇博客,感觉挺有意思的,于是便编程分别实现了三种魔幻矩阵的c程序。

下面是关于魔幻矩阵的一篇很详细的解释说明,看代码之前,务必先去了解了解。

http://blog.csdn.net/northwolves/article/details/1796696





/*
@note    阅读代码前,请先参考以下博客中对于魔幻矩阵的算法讲解
@add     http://blog.csdn.net/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++)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值