类似于机器人路线规划那个题,把走的方向存起来,模拟行进路线,用数组标记走过的位置。
class Solution {
private:
static constexpr int direction[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) return {};
int nrows = matrix.size();
int ncols = matrix[0].size();
vector<vector<bool>> visited(nrows, vector<bool>(ncols));
int length = nrows * ncols;
vector<int>ans(length);
int row = 0;
int col = 0;
int nextRow = 0; int nextCol = 0;int directionst = 0;
for(int i = 0; i < length;i++)
{
visited[row][col] = true;
ans[i] = matrix[row][col];
nextRow = row + direction[directionst][0];
nextCol = col + direction[directionst][1];
if(nextCol < 0 ||nextRow <0 ||nextRow >= nrows ||nextCol >= ncols ||visited[nextRow][nextCol])
{
directionst = (directionst + 1) % 4;
}
row += direction[directionst][0];
col += direction[directionst][1];
}
return ans;
}
};
能写出这样的代码我觉得得是个中等题嗷