给你一个 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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int row=matrix.size();
int col=matrix[0].size();
vector<vector<bool>>visited(row,vector<bool>(col,false));
vector<int>ret;
int i=0;
int j=0;
ret.push_back(matrix[0][0]);
visited[0][0]=true;
int count=row*col;
int num=1;
while(1)
{
if(num>=count)
{
break;
}
//right
while(j+1<col && visited[i][j+1]==false)
{
ret.push_back(matrix[i][j+1]);
visited[i][j+1]=true;
j=j+1;
num++;
}
//down
while(i+1<row && visited[i+1][j]==false)
{
ret.push_back(matrix[i+1][j]);
visited[i+1][j]=true;
i=i+1;
num++;
}
//left
while(j-1>=0 && visited[i][j-1]==false)
{
ret.push_back(matrix[i][j-1]);
visited[i][j-1]=true;
j=j-1;
num++;
}
//up
while(i-1>=0 && visited[i-1][j]==false)
{
ret.push_back(matrix[i-1][j]);
visited[i-1][j]=true;
i=i-1;
num++;
}
}
return ret;
}