|
发表于 2019-12-4 19:16:52
|
显示全部楼层
本楼为最佳答案
本帖最后由 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[y][x] = 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;
- }
- }
复制代码 |
|