当前位置:网站首页>二维数组实战:螺旋矩阵
二维数组实战:螺旋矩阵
2022-07-28 05:26:00 【步步高升b】
给定一个正整数n,按从外向内的螺旋顺序打印1到n^2的所有值。
输入
3
输出
1 2 3
8 9 4
7 6 5
模拟顺时针“画”矩阵的过程:
1.从左到右填充上行
2.从上到下填充右列
3.从右到左填充下行
4.从下到上填充左列
注意:矩阵的四条边都要坚持一致的左闭右开或左开右闭的原则,这样才能按照统一的规则“画”下去。
按照左闭右开的原则画圈,如图所示:

图中每一个箭头覆盖的长度表示一条边遍历的长度,可以看出每一个拐角处的处理规则,在拐角处开始画一条新的边,这里的左闭右开就是不变量,写代码时要坚持这个不变量,就能正确的把这个圈画出来。
代码
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int a[20][20];
int t = 1;
int n, i, j, startx,starty;
cin>>n;
int count = n / 2;
startx = 0;
starty = 0;//设置数组初位置
while (count--) {
for (j = starty; j < n - starty - 1; j++) {
a[startx][j] = t++;
}
for (i = startx; i < n - startx - 1; i++) {
a[i][j] = t++;
}
for (; j > starty; j--) {
a[i][j] = t++;
}
for (; i > startx; i--) {
a[i][j] = t++;
}
startx += 1;
starty += 1;
}
if (n % 2 != 0) a[n/2][n/2] = t;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
cout<<setiosflags(ios::left);//设置左对齐,在头文件<iomanip>中
cout<<setw(4)<<a[i][j];
}
cout<<endl;
}
}边栏推荐
猜你喜欢
随机推荐
气传导耳机哪个好、性价比最高的气传导耳机推荐
error: redefinition of ‘xxx‘
新的selenium
What's a good gift for your girlfriend on the Chinese Valentine's day in 2022? Practical and beautiful gift recommendation
Filter
【动态规划--买卖股票的最佳时期系列2】
小程序:wsx脚本
scrapy 定时执行
2022-05-15 based on JWT token
qt实现将相关信息输出到日志文件
Relative path and absolute path
Use and safe shutdown of qthread thread in QT
QT parse string into JSON data and parse
Getting started with hugging face
Treasure plan TPC system development DAPP construction
2022-06-07 六.日志实现
Leetcode 刷题日记 剑指 Offer II 048. 序列化与反序列化二叉树
2022-06-07 VI. log implementation
气导贴耳式耳机推荐、不需要佩戴入耳的气传导耳机
开放式耳机有哪些、四款音质超好的气传导耳机推荐









