54. 螺旋矩阵
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int Rows = matrix.size(), Cols = matrix.front().size();
// This looks clumsy at the first place, but it's really easy to get if you
// just draw the trail on paper.
int R = Cols, B = Rows - 1, L = Cols - 1, T = Rows - 2;
// This naughty -1 also comes from the counting method above.
int X = -1, Y = 0;
vector<int> Result;
int Remaining = Rows * Cols;
while (Remaining) {
for (int i = 0; i < R; ++i) {
Result.push_back(matrix[Y][++X]);
if (!--Remaining) return Result;
}
R -= 2;
for (int i = 0; i < B; ++i) {
Result.push_back(matrix[++Y][X]);
if (!--Remaining) return Result;
}
B -= 2;
for (int i = 0; i < L; ++i) {
Result.push_back(matrix[Y][--X]);
if (!--Remaining) return Result;
}
L -= 2;
for (int i = 0; i < T; ++i) {
Result.push_back(matrix[--Y][X]);
if (!--Remaining) return Result;
}
T -= 2;
}
return Result;
}
};
这种题到底是用来干什么的呢……我真的是。以后就按我这么写吧,丑是丑了点,但是特别特别好记。