当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
随机推荐
一道[CSCCTF 2019 Qual]FlaskLight的详解再遇SSTI
TiCDC迁移-TiDB到MySQL测试
.NET深入解析LINQ框架(五:IQueryable、IQueryProvider接口详解)
2022年制冷与空调设备运行操作特种作业证考试题库及模拟考试
NAT/NAPT地址转换(内外网通信)技术详解【华为eNSP】
Win11系统重装用什么好 一键重装Win11教程
yuv420sp转jpg
关于DSP驱动外挂flash
命里有时终须有--记与TiDB的一次次擦肩而过
反序列化漏洞
Redis 内存满了怎么办?这样置才正确!
张朝阳对话俞敏洪:谈宇宙、谈焦虑、谈创业、谈退休、谈人生
ps如何换背景颜色,自学ps软件photoshop2022,3种不同的方式笔记记录
GBsae 8c 数据库使用中报错,肿么办?
并发编程之生产者和消费者问题
关于技术学习的6个观点
【无标题】
Ansible deployment scripts - pro available without pit
MySQL binlog都有哪些模式?
Apache Druid 实时分析数据库入门介绍