华为机试题——HJ35 蛇形矩阵

描述

蛇形矩阵是由1开始的自然数依次排列成的一个矩阵上三角形。

例如,当输入5时,应该输出的三角形为:

1 3 6 10 15

2 5 9 14

4 8 13

7 12

11

输入描述:

输入正整数N(N不大于100)

输出描述:

输出一个N行的蛇形矩阵。

示例1

输入:

4

复制输出:

1 3 6 10
2 5 9
4 8
7
#include <iostream>
#include <string.h>
#include <algorithm>
#include <algorithm>
#include <string.h>
#include <sstream>
std::string itoa(int num)
{
    std::stringstream oss;
    oss <<  num;
    return oss.str();
}

void SerpentialMatrix(int n)
{
    std::string arr[n][n];
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            arr[i][j] = "";
        }
    }

    int count = 1;
    for(int i = 0; i < n; ++i)
    {

        int caseNum = i;
        int tempi = i;
        for(int j = 0; j < n; ++j)
        {
            while(caseNum-- >= 0)
            {
                arr[tempi][j] = itoa(count);  
                count++;
                break;
            }
            tempi--;
        }
    }
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            std::cout << arr[i][j] << " ";
        }
        std::cout << std::endl;
    }
    
}

int main()
{
    int n;
    std::cin >> n;
    SerpentialMatrix(n);
    

    return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值