奇数魔幻矩阵生成算法
来源:互联网 发布:微信投诉页面源码 编辑:程序博客网 时间:2024/04/28 21:05
所谓奇数魔幻矩阵就是n*n的矩阵(n为奇数)变换成行,列以及对角线的和都相等! 首先了解其生成法则: 1 ,第一个数字在第一行的中间位置 2,在最新插入的右上角插入接下来的数,如果向上超出了界限,在最行的最后一行插入,如果右超出了界限,在行的最左边插入 3.如果插入数为n的倍数,则在列下放插入
程序 :
#include"stdlib.h"
#include"stdio.h"
#include"time.h"
int **arrMetrix ; // the magic metrix
int n ; // the v
void createMagicMetrix () //depend on the rule to create magic metrix to create metrix
{
int num = 1 ;
arrMetrix[0][n/2] = num ;
int x = 0 , y = n/2 ;
while ( num < n*n )
{
if ( num % n == 0 )
{
x ++ ;
}
else if ( x - 1 < 0 )
{
y ++ ;
x = n - 1 ;
}
else if ( y + 1 > n - 1 )
{
x -- ;
y = 0 ;
}
else if ( x - 1 >= 0 && y + 1 <= n - 1)
{
x -- ;
y ++ ;
}
num ++ ;
arrMetrix[x][y] = num ;
}
}
void printMetrix ()
{
for ( int i = 0 ; i < n ; i ++ )
{
for ( int j = 0 ; j < n ; j ++ )
printf("%3d",arrMetrix[i][j]) ;
printf(" ");
}
}
int main()
{
printf("please input the number of row:");
scanf("%d",&n );
if ( n % 2 == 0 )
{
printf("please make sure the number is odd number ");
exit(0);
}
arrMetrix = ( int ** )malloc ( sizeof(int*) * n ); //apply space for the two v array
for ( int i = 0 ; i < n ; i ++ )
arrMetrix[i] = (int *) malloc(sizeof(int)*n);
createMagicMetrix ();
printMetrix () ;
return 0;
}
#include"stdio.h"
#include"time.h"
int **arrMetrix ; // the magic metrix
int n ; // the v
void createMagicMetrix () //depend on the rule to create magic metrix to create metrix
{
int num = 1 ;
arrMetrix[0][n/2] = num ;
int x = 0 , y = n/2 ;
while ( num < n*n )
{
if ( num % n == 0 )
{
x ++ ;
}
else if ( x - 1 < 0 )
{
y ++ ;
x = n - 1 ;
}
else if ( y + 1 > n - 1 )
{
x -- ;
y = 0 ;
}
else if ( x - 1 >= 0 && y + 1 <= n - 1)
{
x -- ;
y ++ ;
}
num ++ ;
arrMetrix[x][y] = num ;
}
}
void printMetrix ()
{
for ( int i = 0 ; i < n ; i ++ )
{
for ( int j = 0 ; j < n ; j ++ )
printf("%3d",arrMetrix[i][j]) ;
printf(" ");
}
}
int main()
{
printf("please input the number of row:");
scanf("%d",&n );
if ( n % 2 == 0 )
{
printf("please make sure the number is odd number ");
exit(0);
}
arrMetrix = ( int ** )malloc ( sizeof(int*) * n ); //apply space for the two v array
for ( int i = 0 ; i < n ; i ++ )
arrMetrix[i] = (int *) malloc(sizeof(int)*n);
createMagicMetrix ();
printMetrix () ;
return 0;
}
运行结果:
please input the number of row:3
8 1 6
3 5 7
4 9 2
please input the number of row:5
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
- 奇数魔幻矩阵生成算法
- 奇数魔幻矩阵
- 数学问题(四)之魔幻奇数矩阵(行,列,对角线和相等)
- 魔幻矩阵全解(有全部代码说明)
- 生成n*n蛇形矩阵的算法
- 生成n*n蛇形矩阵的算法
- directx中变换矩阵生成算法
- 算法系列-----矩阵(一)-------------单位矩阵的生成
- 奇数魔方矩阵的实现
- 奇数连乘算法
- 基于矩阵实现的最小生成树算法
- 邻接矩阵基础的Prime算法(最小生成矩阵)
- 平面魔方矩阵(奇数,右上方向)
- 魔幻数字
- 魔幻计时器
- 魔幻数字
- 矩阵算法
- 矩阵算法
- ASP.NET2.0下含有CheckBox的GridView删除选定记录实例
- JAVA面试题集
- 控制监视器开关
- 是否再回CSDN安个家?
- TAO[一] .NET项目开发最佳实践
- 奇数魔幻矩阵生成算法
- 工作日志( 2006.12.27--12.28
- 你的快乐是第几等的?
- BES comcat不能正常启动
- 电子书下载
- TAO[二] .NET开发最佳实践(第一章)
- Windows Live Space 与 CSDN Blog , 对我而言的区别
- TAO[三] 第二章 项目管理框架
- 从coding到技术专家