给定一个10阶的螺旋三角,如下所示,你的任务就是输出任意n阶的螺旋三角
1 2 3 4 5 6 7 8 9 10
27 28 29 30 31 32 33 34 11
26 45 46 47 48 49 35 12
25 44 54 55 50 36 13
24 43 53 51 37 14
23 42 52 38 15
22 41 39 16
21 40 17
20 18
19
这个题目有点像LeetCode中的螺旋矩阵问题,只不过这里换成了三个循环,并且每次循环过后,要处理变量。
#include<iostream>
#include<vector>
using namespace std;
void printRectangle(int n, vector<vector<int>>& v) {
int num = 1;
int row_start = 0;
int row_end = n - 1;
int col_start = 0;
int col_end = n - 1;
while (true) {
for (int i = col_start; i <= col_end; i++) {
v[row_start][i] = num++;
}
row_start++;
if (row_start > row_end) break;
int col = col_end - 1;
for (int i = row_start; i <= row_end; i++) {
v[i][col--] = num++;
}
row_end--;
if (row_end < row_start) break;
for (int i = row_end; i >= row_start; i--) {
v[i][col_start] = num++;
}
col_start++;
col_end = col_end - 2; //这里需要注意 col_end 每轮需要减2 因为每轮添加了两列
row_end = row_end - 1; // row_end 每轮也需要减2 但前面减过一个1,因此只需要减1
if (col_start > col_end) break;
}
}
int main() {
int n;
cin >> n;
vector<vector<int>>v(n, vector<int>(n, 0));
printRectangle(n, v);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (v[i][j] != 0) {
cout << v[i][j] << "\t";
}
else {
cout << "\t";
}
}
cout << endl;
}
return 0;
}