给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[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)
{
int m=matrix.size(),n=matrix[0].size();
if(m==0||n==0)
{
return {};
}
vector<int> result;
vector<vector<bool>> visited(m,vector<bool>(n,false));//遍历以后则标记true
int left=0,right=n-1;
int up=0,down=m-1;
while(left<=right&&up<=down)
{
for(int i=left;i<=right;++i)
{
if(!visited[up][i])
{
result.push_back(matrix[up][i]);
visited[up][i]=true;
}
}
for(int j=up+1;j<=down;++j)
{
if(!visited[j][right])
{
result.push_back(matrix[j][right]);
visited[j][right]=true;
}
}
if(left<=right&&up<=down)
{
for(int i=right-1;i>left;--i)
{
if(!visited[down][i])
{
result.push_back(matrix[down][i]);
visited[down][i]=true;
}
}
for(int j=down;j>up;--j)
{
if(!visited[j][left])
{
result.push_back(matrix[j][left]);
visited[j][left]=true;
}
}
}
left++;
right--;
up++;
down--;
}
return result;
}
};