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 43 5 76 9 8分析:给你与1个奇数n, 让你构造一个n * n 的矩阵,要求保证这个矩阵的每行每列和主对角线上数字的和为奇数。构造:
1 #include<bits/stdc++.h> 2 using namespace std; 3 int ans[50][50]; 4 5 int main() 6 { 7 int n; 8 ios::sync_with_stdio(false); 9 cin.tie(0); 10 cin >> n; 11 memset(ans,0,sizeof(ans)); 12 int num1 = 1,num2 =2,cnt1 = (n+1)/2,cnt2 = (n+1)/2; 13 for(int i = 1; i <= n; i++) 14 { 15 for(int j = 1; j <= n; j++) 16 { 17 if(abs(cnt1 - i) + abs(cnt2 - j) <= n/2) // 为什么这么写,有点不清楚 18 ans[i][j] = num1,num1 += 2; 19 else 20 ans[i][j] = num2,num2 += 2; 21 } 22 } 23 for(int i = 1; i <= n; i++) 24 { 25 for(int j = 1; j< n; j++) 26 { 27 printf("%d ",ans[i][j]); 28 } 29 printf("%d\n",ans[i][n]); 30 } 31 return 0; 32 }
n阶幻方:
1 # include <stdio.h> 2 # include <string.h> 3 int g[50][50]; 4 int main(){ 5 int i, j, k, n, x, y, r, c; 6 memset(g, 0, sizeof(g)); 7 scanf("%d", &n); 8 r=1; c=(1+n)/2; 9 g[1][c]=1; 10 11 for(i=2; i<=n*n; i++){ 12 x=r;y=c; 13 x=x-1; 14 if(x<1){ 15 x=n; 16 } 17 y=y+1; 18 if(y>n){ 19 y=1; 20 } 21 if(g[x][y]){ 22 g[r+1][c]=i; 23 r=r+1; 24 } 25 else{ 26 g[x][y]=i; 27 r=x;c=y; 28 } 29 } 30 for(i=1; i<=n; i++){ 31 for(j=1; j<=n; j++){ 32 if(j!=n) 33 printf("%d ", g[i][j]); 34 else{ 35 printf("%d\n", g[i][j]); 36 } 37 } 38 39 } 40 return 0; 41 }
时间: 2024-11-06 18:56:15