054 Spiral Matrix 旋转打印矩阵
2024-09-04 15:03:46
给出一个 m x n 的矩阵(m 行, n 列),请按照顺时针螺旋顺序返回元素。
例如,给出以下矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
应该返回 [1,2,3,6,9,8,7,4,5]。
详见:https://leetcode.com/problems/spiral-matrix/description/
Java实现:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<Integer>();
if(matrix==null||matrix.length==0){
return res;
}
int row=matrix.length;
int col=matrix[0].length; int top=0;
int bottom=row-1;
int left=0;
int right=col-1;
while(top<=bottom&&left<=right){
for(int j=left;j<=right;++j){
res.add(matrix[top][j]);
}
++top;
for(int i=top;i<=bottom;++i){
res.add(matrix[i][right]);
}
--right;
if(top<=bottom){
for(int j=right;j>=left;--j){
res.add(matrix[bottom][j]);
}
}
--bottom;
if(left<=right){
for(int i=bottom;i>=top;--i){
res.add(matrix[i][left]);
}
}
++left;
}
return res;
}
}
C++实现:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty())
return res; int row = matrix.size();
int col = matrix[0].size(); int top = 0;
int bottom = row - 1;
int left = 0;
int right = col - 1; //螺旋曲线,运动轨迹总是一致的
while (top <= bottom && left <= right)
{
//向右列递增遍历
for (int j = left; j <= right; j++)
{
res.push_back(matrix[top][j]);
}
top++; //遍历后,去掉此行 //向下行递增遍历
for (int i = top; i <= bottom; i++)
{
res.push_back(matrix[i][right]);
}
right--; //遍历后,去掉此列 if (top <= bottom) //重要判断,防止重复
{
//向左列递减遍历
for (int j = right; j >= left; j--)
{
res.push_back(matrix[bottom][j]);
} }
bottom--; //遍历后,去掉此行 if (left <= right) //重要判断,防止重复
{
//向上行递减遍历
for (int i = bottom; i >= top; i--)
{
res.push_back(matrix[i][left]);
}
}
left++; //遍历后,去掉此列
} return res;
}
};
最新文章
- Spring学习记录(十一)---使用注解和自动装配
- PHP访问带密码的Redis
- PHP执行定时任务
- centos 下 django 1.8 配置好后 admin 后台无法显示 样式解决办法
- PHP中正则替换函数preg_replace用法笔记
- JS框架整理
- Python 基础篇:字典、集合、文件操作
- destoon实现调用热门关键字的方法
- POJ 2479-Maximum sum(线性dp)
- POJ 2050 Searching the Web
- SharePoint2013 Excel导出好的代码
- WIMP环境搭建
- 工作中MySql的了解到的小技巧
- 生鲜配送管理系统_升鲜宝供应链系统V2.0 设计思想及主要模块,欢迎大家批评指点。
- C# 显示纯文本对齐封装(控制显示字体长度)
- hdu3790 dijkstra+堆优化
- AD7729_双通道Sigma-Delta ADC
- 拦截$.ajax方法实现登录过期登录
- hdu6444 Neko&#39;s Loop
- Snmp学习总结(三)——Win7安装和配置SNMP