当前位置:网站首页>LeetCode 54. 螺旋矩阵 蛇形矩阵式输出字符串
LeetCode 54. 螺旋矩阵 蛇形矩阵式输出字符串
2022-08-04 09:23:00 【超级码力奥】
输入两个整数 n 和 m,输出一个 n 行 m 列的矩阵,将数字 1 到 n×m 按照回字蛇形填充至矩阵中。
具体矩阵形式可参考样例。
输入格式
输入共一行,包含两个整数 n 和 m。
输出格式
输出满足要求的矩阵。
矩阵占 n 行,每行包含 m 个空格隔开的整数。
数据范围
1≤n,m≤100
输入样例:
3 3
输出样例:
1 2 3
8 9 4
7 6 5
原题连接:
https://www.acwing.com/problem/content/758/
// 太优雅了,简直太优雅了。。
// 利用left, right, top, bottom四个变量,来表示矩形的四个边界
// 抽象成每次循环处理一个环
#include<iostream>
using namespace std;
const int N = 105;
int a[N][N];
int n, m;
int main()
{
cin >> n >> m;
int left = 0, right = m - 1, top = 0, bottom = n - 1;
int k = 1;
while(left <= right && top <= bottom)
{
// 处理上部
for(int i = left; i <= right; i ++)
a[top][i] = k ++;
// 处理右部
for(int i = top + 1; i <= bottom; i ++)
a[i][right] = k ++;
// 处理下部,有可能没有下部,所以要多个条件top < bottom
for(int i = right - 1; i >= left && top < bottom; i --)
a[bottom][i] = k ++;
// 处理左部分,有可能没有左部
for(int i = bottom - 1; i > top && left < right; i --)
a[i][left] = k ++;
left ++, right --, top ++, bottom --;
}
for(int i = 0; i < n; i ++)
{
for(int j = 0; j < m; j ++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
边栏推荐
- IDEA 自动导入的配置(Auto import)
- The separation configuration Libpq is supported, speaking, reading and writing
- 《福格行为模型》:如何养成好习惯?
- 字符串与正则表达式(C#)
- Apache APISIX 2.15 版本发布,为插件增加更多灵活性
- Could you please talk about how the website is accessed?[Interview questions in the web field]
- 继承和static关键字
- 交换机链路聚合详解【华为eNSP】
- 他97年的,我既然卷不过他...
- Oracle怎么获取当前库或者同一台服务器上某几个库的数据总行数?
猜你喜欢

思想茶叶蛋 (Jul 31,2022)| 元宇宙(Metaverse)下了一枚什么样的蛋

架构设计杂谈
![Detailed explanation of switch link aggregation [Huawei eNSP]](/img/c2/f9797fe8b17a418466b60cc3dc50a1.png)
Detailed explanation of switch link aggregation [Huawei eNSP]

JSP基本语法

【正点原子STM32连载】第四章 STM32初体验 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1

leetcode经典例题——56.合并区间

After four years of outsourcing, the autumn recruits finally landed

RL学习笔记(一)

MySQL binlog都有哪些模式?

MindSpore:Batchnorm only support nchw input!
随机推荐
LVGL的多语言转换工具--字体设置的好助手
NAT/NAPT地址转换(内外网通信)技术详解【华为eNSP】
RL学习笔记(一)
已解决No module named ‘flask_misaka‘【BUG解决】
LVGL's multi-language conversion tool -- a good assistant for font settings
MindSpore:图算融合报错
cannot import name 'import_string' from 'werkzeug' [bug solution]
Apache APISIX 2.15 版本发布,为插件增加更多灵活性
MindSpore:【model_zoo】【resnet】尝试用THOR优化器运行时报cannot import name ‘THOR‘
VRRP + MSTP configuration, huawei eNSP experiment 】 【
MySQL binlog都有哪些模式?
.NET深入解析LINQ框架(五:IQueryable、IQueryProvider接口详解)
各位大佬,请问mysql数据的cdc,能指定存量数据同步的zone为utc 吗
LeetCode中等题之旋转图像
用OpenGL绘制winXP版扫雷的笑脸表情
《福格行为模型》:如何养成好习惯?
优炫数据库只有数据文件如何恢复
蜜芽CEO刘楠:垂直电商黄金时代已落幕 坚定转型品牌之路
TCP的四次挥手
云函数实现网站自动化签到配置详解【Web函数/Nodejs/cookie】