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.
Example
Input
1
Output
1
Input
3
Output
2 1 4
3 5 7
6 9 8
题意
给出1~n^2个数,将其填入n*n的矩阵,并保证每行每列,主对角线的和都为奇数。(n为奇数)
解题思路:
偶+偶=偶 奇+偶=奇 奇+奇=偶 由此可得出每行每列每对角线只要保证都有奇数个奇数就可以了。
然后发现了规律
1:
奇
3:
偶奇偶
奇奇奇
偶奇偶
5:
偶偶奇偶偶
偶奇奇奇偶
奇奇奇奇奇
偶奇奇奇偶
偶偶奇偶偶
即可找出规律
法二:
直接按照幻方的构造方法。
下贴出法二的代码
#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
ll power(ll a,ll b)
{
ll x=1,y=a;
while(b)
{
if(b&1) x=x*y;
y*=y;
b>>=1;
}
return x;
}
int huanfang[55][55];
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(huanfang,0,sizeof huanfang);
int cao=n*n;
int i=cao+1+n;
int j=n/2+cao-1+n;
int flag=1;
for(int ii=1;ii<=cao;ii++)
{
if(huanfang[(i-1)%n][(j+1)%n])
{
i+=1;
huanfang[i%n][j%n]=ii;
flag=0;
}
else
{
i--;
j++;
huanfang[i%n][j%n]=ii;
flag=1;
}
//for(int ii=0;ii<n;ii++)
//{
// for(int j=0;j<n;j++)
// {
// printf("%d ",huanfang[ii][j]);
// }
// cout<<endl;
//}
//cout<<endl;
}
for(int ii=0;ii<n;ii++)
{
for(int j=0;j<n;j++)
{
printf("%d ",huanfang[ii][j]);
}
cout<<endl;
}
}
return 0;
}