- 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.
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
{ 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:
Wts the logic behind this code??
Post a Comment