描述
蛇形矩阵是由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>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
int i = 1, j = n, shownum = 0, cnt = 0;
bool flag = true;
int coladdval = 0;
for (; i <= n; i++) //n=4时, 4行
{
cnt = i+1; //每行起始第一个数字递增项渐增
for (; j >= 1; j--) //每行的列递减
{
if (flag) //每行第一个输出
{
shownum = i + coladdval;
cout << shownum << " ";
flag = false;
}
else //每行其他列输出
{
shownum += cnt;
cout << shownum << " ";
cnt++;
}
}
j = n - i; //控制每列输出
flag = true;
coladdval += i - 1;
cout << "\n";
}
// n = 0;
}
return 0;
}
再给个漂亮的
#include<iostream>
using namespace std;
int main()
{
int a;
while (cin >> a)
{
int m = 1;
int n;
for (int i = 0; i < a; i++)
{
m += i;
for (int j = i; j < a; j++)
{
int c = 1 + j;
if (j == i)
{
n = m;
cout << n << " ";
}
else {
cout << (n += c) << " ";
}
}
cout << endl;
}
}
}