当前位置:网站首页>[leetcode]Spiral Matrix II
[leetcode]Spiral Matrix II
2022-07-07 04:06:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack
A narrative statement of the problem :
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example, Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]The basic idea :
This topic is the last one 《Spiral Matrix》 Deformation of . It can be assigned with the same traversal method . Create a rotation matrix .
Code :
vector<vector<int> > generateMatrix(int n) { //C++
vector<vector<int> >result;
if(n <=0 )
return result;
for(int i = 0; i < n; i++){
vector<int> tmp(n,0);
result.push_back(tmp);
}
int rowBegin = 0;
int rowEnd = n-1;
int colBegin = 0;
int colEnd = n-1;
int count = 1;
while(rowBegin <= rowEnd && colBegin <= colEnd){
//to right
for(int j = colBegin; j <= colEnd; j++)
result[rowBegin][j] =count++;
rowBegin++;
//to down
for(int j = rowBegin; j <= rowEnd; j++)
result[j][colEnd] = count++;
colEnd--;
//to left
if(rowBegin <= rowEnd){
for(int j = colEnd; j >= colBegin; j--)
result[rowEnd][j] = count++;
}
rowEnd--;
//to up
if(colBegin <= colEnd){
for(int j = rowEnd; j >= rowBegin; j--)
result[j][colBegin] = count++;
}
colBegin++;
}
return result;
}Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/116707.html Link to the original text :https://javaforall.cn
边栏推荐
猜你喜欢

When QT uses qtooltip mouse to display text, the picture of the button will also be displayed and the prompt text style will be modified

【系统管理】清理任务栏的已删除程序的图标缓存

Kotlin Android environment construction
接口数据安全保证的10种方式

Analysis on urban transportation ideas of 2022 Zhongqing cup C

Optimization cases of complex factor calculation: deep imbalance, buying and selling pressure index, volatility calculation

What is the experience of maintaining Wanxing open source vector database

It's too convenient. You can complete the code release and approval by nailing it!

2022年电工杯B 题 5G 网络环境下应急物资配送问题思路分析

web服务性能监控方案
随机推荐
Mongo shell, the most complete mongodb in history
ERROR: Could not build wheels for pycocotools which use PEP 517 and cannot be installed directly
二叉搜索树的实现
UltraEdit-32 温馨提示:右协会,取消 bak文件[通俗易懂]
超越Postman,新一代国产调试工具Apifox,用起来够优雅
Restore backup data on GCS with br
【开发软件】 tilipa开发者软件
Web service performance monitoring scheme
预处理——插值
硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件
数据的存储
Probability formula
史上最全MongoDB之安全认证
机器人(自动化)课程的持续学习-2022-
Summer 2022 daily question 1 (1)
vim —- 自己主动的按钮indent该命令「建议收藏」
【刷题记录】2. 两数相加
Imitate Tengu eating the moon with Avatar
【OA】Excel 文档生成器: Openpyxl 模块
什么是 CGI,什么是 IIS,什么是VPS「建议收藏」