Monday, June 28, 2010

Simple C Code to Create Magic matrix

First we have to understand what is magic matrix.
  •   In magic matrix every rows and column sums are equal.
  •   Diagonal sum is also equal.
  •   The following code has O(n^2) time complexity.
  •   The example for magic matrix is given below.
               8     1       6
                               
               3      5      7        //rows,column,diagonal sum are equal
                      
               4      9      2       //here n is 3


Here is the code
 
   void magic_matrix(int n)          // N should be odd number...
   {   int i,j,k,num=1;            
        i=1;
        j=(1+n)/2;
        for(k=0;k < n*n;k++)  
        { a[i-1][j-1]=num;num++;
           i--;
           j++;
           if(i==0) i=n;
           if(j==n+1) j=1;
           if(a[i-1][j-1]!=0)
          { i+=2;
            j--;
            if(i>n) i=i-n;
            if(j==0) j=n;
           }
         }
    for(i=0;i < n;i++)
    {for(j=0;j < n;j++)
      { printf("%d\t",a[i][j]);
       }
      printf("\n");              
       }
 }

1 comment:

Unknown said...

Wts the logic behind this code??