当前位置:网站首页>[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
边栏推荐
猜你喜欢
Confirm the future development route! Digital economy, digital transformation, data This meeting is very important
Implementation of map and set
机器人(自动化)课程的持续学习-2022-
Imitate Tengu eating the moon with Avatar
ABAP 動態內錶分組循環
机械臂速成小指南(十):可达工作空间
How to detect whether the MySQL code runs deadlock +binlog view
Simple implementation of AVL tree insertion and verification operations
复杂因子计算优化案例:深度不平衡、买卖压力指标、波动率计算
Analysis on urban transportation ideas of 2022 Zhongqing cup C
随机推荐
Class constant pool and runtime constant pool
复杂因子计算优化案例:深度不平衡、买卖压力指标、波动率计算
三重半圆环进度条,直接拿去就能用
超越Postman,新一代国产调试工具Apifox,用起来够优雅
Native MySQL
【knife-4j 快速搭建swagger】
Construction of Hisilicon universal platform: color space conversion YUV2RGB
机械臂速成小指南(十):可达工作空间
CUDA Programming
使用Thread类和Runnable接口实现多线程的区别
The most complete deployment of mongodb in history
如何检测mysql代码运行是否出现死锁+binlog查看
How to detect whether the MySQL code runs deadlock +binlog view
POJ培训计划2253_Frogger(最短/floyd)
如何编写一个程序猿另一个面试官眼前一亮的简历[通俗易懂]
Optimization cases of complex factor calculation: deep imbalance, buying and selling pressure index, volatility calculation
Leetcode: interview question 17.24 Maximum cumulative sum of submatrix (to be studied)
维护万星开源向量数据库是什么体验
One of oscp tools: dirsearch usage Encyclopedia
10 ways of interface data security assurance