文章目录
leetcode54:54. 螺旋矩阵
题目描述
给定一个包含 m x n
个元素的矩阵(m
行, n
列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
Example
输入:[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出:[1,2,3,6,9,8,7,4,5]
solution idea
按层模拟
class Solution {
/*
** 按层模拟
*/
private:
vector<int > res;
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m=matrix.size();
if(m==0) return res;
int n=matrix[0].size();
int r1=0,r2=m-1,c1=0,c2=n-1;//(r1,c1),(r2,c2)当前层左上角、右下角
while(r1<=r2 && c1<=c2)
{
for(int c=c1;c<=c2;c++) res.push_back(matrix[r1][c]); // 添加r1行
for(int r=r1+1;r<=r2;r++) res.push_back(matrix[r][c2]); // 添加c2列
if(r1<r2 && c1<c2)
{
for(int c=c2-1;c>c1;c--) res.push_back(matrix[r2][c]); // 添加r2列
for(int r=r2;r>r1;r--) res.push_back(matrix[r][c1]); // 添加c1列
}
r1++;
r2--;
c1++;
c2--;
}
return res;
}
};
参考文献
- c++ prime 第5版