NYOJ 734 奇数阶魔方

奇数阶魔方

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 3
描述
一个 n 阶方阵的元素是1,2,...,n^2,它的每行,每列和2条对角线上元素的和相等,这样 的方阵叫魔方。n为奇数时我们有1种构造方法,叫做“右上方” ,例如下面给出n=3,5,7时 的魔方.
3
8 1 6
3 5 7
4 9 2
5
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
7
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
第1行中间的数总是1,最后1行中间的数是n^2,他的右边是2,从这三个魔方,你可看出“右 上方”是何意。 
输入
包含多组数据,首先输入T,表示有T组数据.每组数据1行给出n(3<=n<=19)是奇数。
输出
对于每组数据,输出n阶魔方,每个数占4格,右对齐
样例输入
2
3
5
样例输出
   8   1   6
   3   5   7
   4   9   2
  17  24   1   8  15
  23   5   7  14  16
   4   6  13  20  22
  10  12  19  21   3
  11  18  25   2   9
来源
#include <cstdio>
#include <cmath>
#include <queue>
#include <cstring>
#include <stack>
#include <map>
#include <vector>
#include <iostream>
#include <algorithm>
#define MAX_N 1005
#define MIN(a, b)   (a < b)? a: b
#define MAX(a, b)   (a > b)? a: b
using namespace std;
int pos[MAX_N][MAX_N];
int main() {
    int t, n;
    scanf("%d", &t);
    while (t--) {
        memset(pos, 0,sizeof(pos));
        scanf("%d", &n);
        int temp = 1, cnt = 0, cut = n / 2;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                pos[cnt][cut] = temp++;
                if (j == n - 1) {
                    cnt += 1;
                    cut;
                    if (cnt > n - 1) {
                        cnt = n - cnt;
                    }
                    continue;
                }
                cnt--, cut++;
                if (cnt < 0) {
                    cnt += n;
                }
                if (cut > n - 1) {
                    cut = n - cut;
                }

            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                printf("%4d", pos[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值