Codeforces 710C-Magic Odd Square

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 from1 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


解:魔方矩阵的变形,输入一个奇数n,形成一个n*n的矩阵,使得矩阵的每一行,每一列,两个对角线都是奇数。

因为输入为奇数,所以直接利用魔方矩阵的思路做就可以了。

#include <stdio.h>
#include <stdlib.h>

void CalculateOddMagicSquare(int n)
{
  int matrix[50][50];

  int nsqr = n * n;
  int i=0, j=n/2;    

  for (int k=1; k<=nsqr; ++k) 
  {
    matrix[i][j] = k;

    i--;
    j++;

    if (k%n == 0) 
    { 
      i += 2; 
      --j; 
    }
    else 
    {
      if (j==n) 
        j -= n;
      else if (i<0) 
        i += n;
    }
  }
  for(int i=0;i<n;i++){
  	for(int j=0;j<n-1;j++){
  		printf("%d ",matrix[i][j]);
  	}
  	printf("%d\n",matrix[i][n-1]);
  }
}
int main()
{
	int n;
	while(~scanf("%d",&n)){
		CalculateOddMagicSquare(n);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值