从 4 个转向中周期选取
directIdx = (directIdx + 1) % 4;
int nextRow = r + directions[directIdx][0];
int nextColumn = c + directions[directIdx][1];
r += directions[directIdx][0];
c += directions[directIdx][1];
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int row = matrix.size();
if (row == 0) {
return {};
}
int column = matrix[0].size();
if (column == 0) {
return {};
}
std::vector<std::vector<bool>> visited(row, std::vector<bool>(column));
int sz = row * column;
std::vector<int> order(sz);
int r = 0;
int c = 0;
int directIdx = 0;
for (int i = 0; i < sz; ++i) {
order[i] = matrix[r][c];
visited[r][c] = true;
int nextRow = r + directions[directIdx][0];
int nextColumn = c + directions[directIdx][1];
if (nextRow < 0 || nextRow >= row ||
nextColumn < 0 || nextColumn >= column ||
visited[nextRow][nextColumn]) {
directIdx = (directIdx + 1) % 4;
}
r += directions[directIdx][0];
c += directions[directIdx][1];
}
return order;
}
private:
static constexpr int directions[4][2] = {
// right
{0, 1},
// down
{1, 0},
// left
{0, -1},
// up
{-1, 0}
};
};