描述
蛇形矩阵是由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;
}