C. Magic Odd Square
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
Input
The only line contains odd integer n (1 ≤ n ≤ 49).
Output
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
Examples
input
1
output
1
input
3
output
2 1 4 3 5 7 6 9 8
奇数幻方:即一个由1~n*n的数字组成的n*n的方阵的每行、列及对角线的数字的和为奇数
奇数阶幻方构造法
(1) 将1放在第一行中间一列;
(2) 从2开始直到n×n止各数依次按下列规则存放:按 45°方向行走,向右上,即每一个数存放的行比前一个数的行数减1,列数加1
(3) 如果行列范围超出矩阵范围,则回绕。例如1在第1行,则2应放在最下一行,列数同样加1;
(4) 如果按上面规则确定的位置上已有数,或上一个数是第1行第n列时,则把下一个数放在上一个数的下面。
n=3时
![]() |
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int main(){
int n, i, j, a[100][100], x, y, h, l;
while(cin>>n){
memset(a, 0, sizeof(a));
a[1][n/2+1] = 1;
x = 1;
y = n/2+1;
for(i=2; i<=n*n; i++){
if(x==1)
h = n;
else
h = x-1;
if(y==n)
l = 1;
else
l = y+1;
if(x==1&&y==n){
a[x+1][y] = i;
x = x+1;
}
else if(a[h][l]==0){
a[h][l] = i;
x = h;
y = l;
}
else{
a[x+1][y] = i;
x = x+1;
}
}
for(i=1; i<=n; i++){
for(j=1; j<=n; j++){
if(j==1)
printf("%d",a[i][j]);
else
printf(" %d",a[i][j]);
}
cout<<endl;
}
}
return 0;
}