跳到主要内容

54 螺旋矩阵

https://leetcode.cn/leetbook/read/top-interview-questions-hard/xw3ng2/

cost:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int x1 = 0, y1 = 0, x2 = matrix.size() - 1, y2 = matrix[0].size() - 1;
enum State {
Right,
Up,
Down,
Left,
};
enum State state = Right;
int x = x1, y = y1;
int n = (x2 + 1) * (y2 + 1);
vector<int> res;
while (n > 0) {
switch (state) {
case Right:
if (y == y2) {
state = Down;
res.push_back(matrix[x][y]);
x1++;
x = x1;
} else {
res.push_back(matrix[x][y]);
y++;
}
break;
case Down:
if (x == x2) {
state = Left;
res.push_back(matrix[x][y]);
y2--;
y = y2;
} else {
res.push_back(matrix[x][y]);
x++;
}
break;
case Left:
if (y == y1) {
state = Up;
res.push_back(matrix[x][y]);
x2--;
x = x2;
} else {
res.push_back(matrix[x][y]);
y--;
}
break;
case Up:
if (x == x1) {
state = Right;
res.push_back(matrix[x][y]);
y1++;
y = y1;
} else {
res.push_back(matrix[x][y]);
x--;
}
break;
}
n--;
}
return res;
}
};