奇数魔幻矩阵生成算法

来源:互联网 发布:微信投诉页面源码 编辑:程序博客网 时间: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;
}

 

运行结果:

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