蛇形矩阵代码
麻烦问一下,下面这个矩阵用C++应该怎么写啊?输入一个正整数n(n<=30),输出n所对应的蛇形矩阵。举两个例子:
n=10时,蛇形矩阵为:
10 9 5 4
8 6 3
7 2
1
n=9时,蛇形矩阵为:
9 8 4 3
7 5 2
6 1 本帖最后由 Croper 于 2019-12-4 19:23 编辑
直观点的方法#include <vector>
#include <math.h>
#include <iostream>
using namespace std;
vector<vector<int>> snakeMatrix(int n) {
int a = ceil((sqrt(8 * n + 1) - 1) / 2); //确定矩阵阶数
vector<vector<int>> matrix(a, vector<int>(a, -1)); //申请一个n阶的矩阵,初始化为-1
for (int i = n, x = 0, y = 0; i > 0; i--) { //按规则循环
matrix = i;
if ((x + y) & 1) {
x--;
y++;
if (x < 0) {
x = 0;
}
}
else {
x++;
y--;
if (y < 0) {
y = 0;
}
}
}
return matrix;
}
代码简短的方法:void printsnakeMatrix(int n) {
int a = ceil((sqrt(8 * n + 1) - 1) / 2);//确定矩阵阶数
for (int y = 0; y < a; ++y) {
for (int x = 0; x + y < a; ++x) {
int l = x + y;
int ans = n - l * (l + 1) / 2 - (l &1? y : x);//计算当前位置的值:在位置(x,y)之前的数,可以分为两部分:1、前面(x+y)阶的三角形数 2、根据奇偶性不同,当前的行序号或列序号
if (ans > 0) {
cout << ans << '\t';
}
}
cout << endl;
}
} Croper 发表于 2019-12-4 19:16
直观点的方法
谢谢啦,很详细,运行了一下,第一个程序到int>>之间需要空格 Croper 发表于 2019-12-4 19:16
直观点的方法
int a = ceil((sqrt(8 * n + 1) - 1) / 2);
麻烦问一下,你这句确定阶数的原理是什么啊 若a阶三角形数的值为a,有
a(a+1)/2=n
带入2次函数求根公式,有
a1=(sqrt(8*n+1)-1)/2;
a2=(-sqrt(8*n+1)-1)/2;
a2肯定是负数,舍去
所以a=(sqrt(8*n+1)-1)/2; Croper 发表于 2019-12-11 22:43
若a阶三角形数的值为a,有
a(a+1)/2=n
带入2次函数求根公式,有
好的,懂了,谢谢啦
页:
[1]