给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
解析:没有什么巧妙的办法,使用算法模拟题目要求操作即可
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int n=matrix.size();
if(n==0) return {};
if(matrix[0].size()==0) return {};
int m = matrix[0].size();
//元素个数
int num = m*n;
//移动方向
int type=0;
//当前坐标
int i=0,j=0;
while(num>0)
{
//只剩一个的特殊情况
if(m==1&&n==1)
{
res.push_back(matrix[i][j]);
--num;
}
//向右
if(type==0){
for(int t=0;t<m-1;++t){
res.push_back(matrix[i][j]);
--num;
if (num == 0) break;
++j;
}
type=1;
}
//向下
else if(type==1){
for(int t=0;t<n-1;++t){
res.push_back(matrix[i][j]);
--num;
if (num == 0) break;
++i;
}
type=2;
}
//向左
else if(type==2)
{
for(int t=0;t<m-1;++t)
{
res.push_back(matrix[i][j]);
--num;
if (num == 0)
break;
--j;
}
type=3;
}
//向上
else if(type==3)
{
for(int t=0;t<n-1;++t)
{
res.push_back(matrix[i][j]);
--num;
if (num == 0) break;
--i;
}
//一个循环结束
++i,++j;
type=0;
m-=2,n-=2;
}
}
return res;
}
};