当前位置:网站首页>[leetcode]Spiral Matrix II
[leetcode]Spiral Matrix II
2022-07-06 21:27:00 【全栈程序员站长】
大家好,又见面了,我是全栈君
问题叙述性说明:
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 ]
]
基本思路:
本题是上一篇《Spiral Matrix》的变形。能够採用相同的遍历方法为其赋值。创建旋转矩阵。
代码:
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;
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/116707.html原文链接:https://javaforall.cn
边栏推荐
- 二叉搜索树的实现
- QT thread and other 01 concepts
- Some common software related
- AVL树插入操作与验证操作的简单实现
- Redis源码学习(30),字典学习,dict.h
- VHDL implementation of single cycle CPU design
- 使用Thread类和Runnable接口实现多线程的区别
- QT item table new column name setting requirement exercise (find the number and maximum value of the array disappear)
- MySQL storage engine
- Top 50 hit industry in the first half of 2022
猜你喜欢
Tencent cloud native database tdsql-c was selected into the cloud native product catalog of the Academy of communications and communications
NoSQL之Redis配置与优化
[hcie TAC] question 3
Summer 2022 daily question 1 (1)
Implementation of map and set
【系统管理】清理任务栏的已删除程序的图标缓存
Hisilicon 3559 universal platform construction: RTSP real-time playback support
Force buckle ----- path sum III
AVL树插入操作与验证操作的简单实现
力扣------路径总和 III
随机推荐
. Net interface can be implemented by default
How to customize the shortcut key for latex to stop running
【编码字体系列】OpenDyslexic字体
Kbone与小程序跨端开发的一些思考
[leetcode] 450 and 98 (deletion and verification of binary search tree)
23. (ArcGIS API for JS) ArcGIS API for JS ellipse collection (sketchviewmodel)
MySQL storage engine
Kotlin Android environment construction
Storage of data
GPT-3当一作自己研究自己,已投稿,在线蹲一个同行评议
我的勇敢对线之路--详细阐述,浏览器输入URL发生了什么
使用 TiDB Lightning 恢复 GCS 上的备份数据
QT opens a file and uses QFileDialog to obtain the file name, content, etc
ABAP 动态内表分组循环
【安全攻防】序列化與反序列,你了解多少?
QT item table new column name setting requirement exercise (find the number and maximum value of the array disappear)
Kotlin Android 环境搭建
tflite模型转换和量化
Tencent cloud native database tdsql-c was selected into the cloud native product catalog of the Academy of communications and communications
Probability formula