给定一个包含 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]
思路:剑指offer的旋转矩阵
代码:
class Solution {
private:
vector<int>ans;
void print(vector<vector<int>>& matrix,int start)
{
int rows = matrix.size();
int cols = matrix[0].size();
int endX = cols - 1 - start;
int endY = rows - 1 - start;
for (int i = start; i <= endX; i++)
ans.push_back(matrix[start][i]);
if (endY > start)
{
for (int i = start + 1; i <= endY; i++)
ans.push_back(matrix[i][endX]);
}
if (endX > start&& endY > start)
{
for (int i = endX - 1; i >= start; i--)
{
ans.push_back(matrix[endY][i]);
}
}
if (start < endX && start < endY - 1)
{
for (int i = endY - 1; i >= start + 1; i--)
{
ans.push_back(matrix[i][start]);
}
}
}
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rows = matrix.size();
//vector<int>ans;
if (rows == 0) return ans;
int cols = matrix[0].size();
int start = 0;
while (start <=rows/2 && start <=cols/2)
{
print(matrix, start);
start++;
}
return ans;
}
};