7-8 螺旋方阵 (20 分) 优美舒适解法,可以说非常舒服了

#include<stdio.h>
int main(void) {
    int n;
    int a[10][10];
    scanf("%d", &n);
    int x = 0, y = 0;//坐标,爱的螺旋转圈圈
    int k = 1;//循环数1~n*n
    int bound0=n-1, bound1=n-1, bound2=0, bound3=1;//右下左上个方向的墙壁会向中间缩拢
    int direction = 0;//0向右,1向下,2向左,3向上
    while(k<=n*n){
        if(direction==0){
            a[x][y++] = k++;
            if (y == bound0) {//向右走,遇到墙壁就向下
                direction = 1;
                bound0--;
            }
        } else if (direction == 1) {
            a[x++][y] = k++;
            if (x == bound1) {//向下走,遇到墙壁就向左
                direction = 2;
                bound1--;
            }
        } else if (direction == 2) {
            a[x][y--] = k++;
            if (y == bound2) {//向左走,遇到墙壁就向上
                direction = 3;
                bound2++;
            }
        } else if(direction == 3)
        {
            a[x--][y] = k++;
            if (x == bound3) {//向上走,遇到墙壁就向右
                direction = 0;
                bound3++;
            }
        }
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            printf(" %2d",a[i][j]);
        }
        printf("\n");
    }
}

 

  • 28
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 21
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值