HLG 1564 螺旋矩阵 (趣味C语言)

本文介绍了一种算法,用于生成指定大小的螺旋矩阵,并详细解释了如何通过循环和条件判断来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接: http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1564


Description
对于给定的一个数n,要你打印n*n的螺旋矩阵。

比如n=3时,输出:

1 2 3
8 9 4
7 6 5

Input

多组测试数据,每个测试数据包含一个整数n(1<=n<=32)

Output

对于每组测试数据,输出一个n*n的螺旋矩阵,定义在题目描述里。

在一组测试数据中,每个数占的字符宽度是该组数据中最大的数位数加1,比如3*3的螺旋矩阵,最大值是9,那么每个数就要占2个字符宽度。

两组测试数据之间用一个空行隔开。

Sample Input
1
2
3
Sample Output
1

1 2
4 3

1 2 3
8 9 4
7 6 5


代码如下:(怀念初学的时候啊~~~)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define MAXN 105
#define RST(N)memset(N, 0, sizeof(N))
using namespace std;

int Kesha[105][105], cas = 0, n;

int main()
{
    while(~scanf("%d", &n)) {
        if(cas++) printf("\n");
        int x, y, ans = 0;
        RST(Kesha);
        ans = Kesha[x=0][y=0] = 1;

        while(ans < n * n) {
            while(y + 1 < n && !Kesha[x][y+1]) Kesha[x][++y] = ++ans;
            while(x + 1 < n && !Kesha[x+1][y]) Kesha[++x][y] = ++ans;
            while(y - 1 >= 0 && !Kesha[x][y-1]) Kesha[x][--y] = ++ans;
            while(x - 1 >= 0 && !Kesha[x-1][y]) Kesha[--x][y] = ++ans;
        }
        int t = n * n;
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                if(t<10) printf("%2d", Kesha[i][j]);
                else if(t>=10 && t<=99) printf("%3d", Kesha[i][j]);
                else if(t>=100 && t<=999) printf("%4d", Kesha[i][j]);
                else if(t >= 1000 ) printf("%5d", Kesha[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值