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. InputThe 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.
构造解。
不难发现所有的奇数都是等价的,所有的偶数也是,所以只要区分奇偶即可。
以n=7为例,如下是一个可行解。
OOOXOOO
OOXXXOO
OXXXXXO
XXXXXXX
OXXXXXO
OOXXXOO
OOOXOOO
其中X代表奇数,O代表偶数。
#include<cstdio>
#include<cstring>
int a[55][55];
int main()
{
int i,j,k,n,x,y,z,mid;
x=1;
y=2;
scanf("%d",&n);
mid=(n+1)/2;
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
if ((i<=mid&&j>=mid-i+1&&j<=mid+i-1)||(i>mid&&j>=i+mid-n&&j<=mid+n-i))
{
printf("%d",x);
x+=2;
}
else
{
printf("%d",y);
y+=2;
}
if (j==n) printf("\n");
else printf(" ");
}
}