class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.size() == 0 || matrix[0].size() == 0)
return {};
int m = matrix.size();
int n = matrix[0].size();
int total = m * n;
vector<int> res(total);
vector<vector<bool>> visited(m, vector<bool>(n));
int direction[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int direct = 0;
int row = 0, col = 0;
for(int i = 0; i < total; i++){
res[i] = matrix[row][col];
visited[row][col] = true;
int nextRow = row + direction[direct][0];
int nextCol = col + direction[direct][1];
if(nextRow >= m || nextRow < 0 || nextCol >= n || nextCol < 0 || visited[nextRow][nextCol] == true){
direct = (direct + 1) % 4;
}
row += direction[direct][0];
col += direction[direct][1];
}
return res;
}
};
08-06
201
05-30