当前位置:网站首页>[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
边栏推荐
- Redis源码学习(31),字典学习,dict.c(一)
- Kotlin Android 环境搭建
- Simple implementation of AVL tree insertion and verification operations
- SSL证书部署
- 机器学习笔记 - 使用机器学习进行鸟类物种分类
- ERROR: Could not build wheels for pycocotools which use PEP 517 and cannot be installed directly
- 力扣------路径总和 III
- 你心目中的数据分析 Top 1 选 Pandas 还是选 SQL?
- 2022夏每日一题(一)
- Delete data in SQL
猜你喜欢
How to detect whether the MySQL code runs deadlock +binlog view
22. (ArcGIS API for JS) ArcGIS API for JS Circle Collection (sketchviewmodel)
什么是 BA ?BA怎么样?BA和BI是什么关系?
Implementation steps of docker deploying mysql8
1200.Minimum Absolute Difference
ABAP 动态内表分组循环
Implementation of map and set
Mysql-数据丢失,分析binlog日志文件
【系统管理】清理任务栏的已删除程序的图标缓存
QT opens a file and uses QFileDialog to obtain the file name, content, etc
随机推荐
QT 项目 表格新建列名称设置 需求练习(找数组消失的数字、最大值)
Codeworks 5 questions per day (1700 average) - day 7
Arduino droplet detection
链表面试常见题
. Net interface can be implemented by default
大白话高并发(二)
23. (ArcGIS API for JS) ArcGIS API for JS ellipse collection (sketchviewmodel)
PIP download only, not install
QT thread and other 01 concepts
数据的存储
Machine learning notes - bird species classification using machine learning
20. (ArcGIS API for JS) ArcGIS API for JS surface collection (sketchviewmodel)
接口数据安全保证的10种方式
Calculation of time and space complexity (notes of runners)
termux设置电脑连接手机。(敲打命令贼快),手机termux端口8022
List interview common questions
22. (ArcGIS API for JS) ArcGIS API for JS Circle Collection (sketchviewmodel)
Docker部署Mysql8的实现步骤
Hisilicon 3559 universal platform construction: RTSP real-time playback support
Implementation of binary search tree