规律
魔方阵是指由1,2,3……n2填充的,每一行、每一列、对角线之和均相等的方阵,阶数n = 3,4,5…。魔方阵也称为幻方阵。
奇魔方(阶数n = 2 * m + 1,m =1,2,3……)规律如下:
数字1位于方阵中的第一行中间一列;
数字a(1 < a ≤ n2)所在行数比a-1行数少1,若a-1的行数为1,则a的行数为n;
数字a(1 < a ≤ n2)所在列数比a-1列数大1,若a-1的列数为n,则a的列数为1;
如果a-1是n的倍数,则a(1 < a ≤ n2)的行数比a-1行数大1,列数与a-1相同。
代码
#include <stdio.h>
#include <string.h>
const int N = 1000;
int mat[N][N];
int n;
void next_pos(int &x, int &y)
{
if(mat[x][y] % n == 0)
{
++x;
return;
}
x = (x == 1) ? n : (x - 1);
y = (y == n) ? 1 : (y + 1);
}
void func()
{
int mid = (n >> 1) + 1;
mat[1][mid] = 1;
int x = 1;
int y = mid;
for(int i = 2, n2 = n * n; i <= n2; ++i)
{
next_pos(x, y);
mat[x][y] = i;
}
}
void print_mat()
{
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
printf("%02d%s", mat[i][j], (j == n) ? "\n" : " ");
puts("");
}
int main()
{
while(~scanf("%d", &n))
{
memset(mat, 0, sizeof mat);
func();
print_mat();
}
}