生成n阶螺旋三角

给定一个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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值