当前位置:网站首页>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;
}
边栏推荐
- JSP基本语法
- Ansible deployment scripts - pro available without pit
- DOM简述
- [Cloud Residency Co-Creation] HCSD Celebrity Live Streaming – Employment Guide
- Anton Paar Anton Paar Density Meter Hydrometer Repair DMA35 Performance Parameters
- Cloud function to achieve automatic website check-in configuration details [Web function/Nodejs/cookie]
- 2022 Cloud Native Computing代表厂商 | 灵雀云第三次入选Gartner中国ICT技术成熟度曲线报告
- 我和 TiDB 的故事 | 缘份在,那就终是能相遇的
- 陈春花发布声明,这场流量狂欢该到了收尾的时候
- TiFlash 源码阅读(五) DeltaTree 存储引擎设计及实现分析 - Part 2
猜你喜欢
记录十条工作中便利的API小技巧
Detailed explanation of switch link aggregation [Huawei eNSP]
云函数实现网站自动化签到配置详解【Web函数/Nodejs/cookie】
Could you please talk about how the website is accessed?[Interview questions in the web field]
我和 TiDB 的故事 | 缘份在,那就终是能相遇的
有了这篇 Kubernetes 的介绍,它的原理秒懂!
MindSpore:【model_zoo】【resnet】尝试用THOR优化器运行时报cannot import name ‘THOR‘
2022年制冷与空调设备运行操作特种作业证考试题库及模拟考试
Detailed Explanation of Addresses Delivered by DHCP on Routing/Layer 3 Switches [Huawei eNSP]
Win11如何隐藏输入法悬浮窗?
随机推荐
请你谈谈网站是如何进行访问的?【web领域面试题】
[Punctuality Atomic STM32 Serial] Chapter 1 Learning Method of the Book Excerpted from [Punctuality Atomic] MiniPro STM32H750 Development Guide_V1.1
SQL后计算的利器
【正点原子STM32连载】第二章 STM32简介 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1
cannot import name 'import_string' from 'werkzeug' [bug solution]
GBsae 8 c database using an error, how to do?
v-model原理,在“radio”、“checkbox”、“select”、修饰符
字符串相关题目
《福格行为模型》:如何养成好习惯?
冰蝎工具开发实现动态二进制加密WebShell
leetcode经典例题——49.字母异位词分组
交换机链路聚合详解【华为eNSP】
LeetCode中等题之旋转图像
Get the number of cpu cores
Apache APISIX 2.15 版本发布,为插件增加更多灵活性
浅聊偏函数
telnet远程登录aaa模式详解【华为eNSP】
【C补充】指针相关知识点收集01
暴力破解ssh/rdp/mysql/smb服务
冰蝎逆向初探