题目:
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
题目链接:Spiral Matrix
C++:
模拟旋转记录
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ret;
if(matrix.size() == 0)
return ret;
int x1 = 0;
int y1 = 0;
int x2 = matrix[0].size() - 1;
int y2 = matrix.size() - 1;
while (x1 <= x2 && y1 <= y2) {
for (int i = x1; i <= x2; i++)
ret.push_back(matrix[y1][i]);
y1++;
for (int i = y1; i <= y2; i++)
ret.push_back(matrix[i][x2]);
x2--;
for (int i = x2; i >= x1 && y1 <= y2; i--)
ret.push_back(matrix[y2][i]);
y2--;
for (int i = y2; i >= y1 && x1 <= x2; i--)
ret.push_back(matrix[i][x1]);
x1++;
}
return ret;
}
};