蛇形填空(紫皮算法书c++例题补充)

#include<iostream>
#include<iomanip>
using namespace std;
int main() {
    const int MAX = 8;
    int a[MAX][MAX] = { 0 };
    int n;
    cin >> n;
    int num = 1;
    int bottom = n - 1, left = 0, right = n - 1, top = 0;
    while (top <= bottom && left <= right) {
        if (top <= bottom) {
            for (int i = left; i <= right; i++)
            {
                a[top][i] = num++;
            }
            top++;
        }
        if (left <= right) {
            for (int i = top; i <= bottom; i++)
            {
                a[i][right] = num++;
            }
            right--;
        }
        if (top <= bottom) {
            for (int i = right; i >= left; i--) {
                a[bottom][i] = num++;
            }
            bottom--;
        }
    
    if (left <= right) {
        for (int i = bottom; i >= top; i--) {
            a[i][left] = num++;
        }
        left++;
    }
}
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        cout<<setw(3) << a[i][j] << " ";
    }
    cout << endl;
}
return 0;
}

看起来简单但是写起来是真要命

改了又改终于是做出来了。

简单说一下四个循环然后边界if来保证不越界。然后最后for循环输出数据。

紫皮书的话是c语言实现的而且代码十分的节俭高度凝练了。我没怎么看明白。所以还是建议初学的话都自己亲自打一打代码。不断的调试。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值