class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.size() == 0 && matrix[0].size() == 0){
return {{}};
}
int left = 0, right = matrix[0].size()-1, top = 0, bottom = matrix.size()-1;
vector<int>res;
while(left <= right && top <= bottom){
for(int i = left; i <= right; i++){
res.push_back(matrix[top][i]);
}
for(int i = top+1; i <= bottom; i++){
res.push_back(matrix[i][right]);
}
if(left < right && top < bottom){
for(int i = right-1; i > left; i--){
res.push_back(matrix[bottom][i]);
}
for(int i = bottom; i > top; i--){
res.push_back(matrix[i][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return res;
}
};
|