Given an m x n
matrix, return all elements of the matrix in spiral order.
Solution
点击查看代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int r = matrix.size(), c = matrix[0].size();
vector<int> ans;
int top = 0, down = r-1, left = 0, right = c-1;
int dir=0;
while(top<=down && left<=right){
if(dir==0){
for(int i=left;i<=right;i++)
ans.push_back(matrix[top][i]);
dir=1;
top++;
}
else if(dir==1){
for(int i=top;i<=down;i++)
ans.push_back(matrix[i][right]);
dir=2;
right--;
}
else if(dir==2){
for(int i=right;i>=left;i--)
ans.push_back(matrix[down][i]);
dir=3;
down--;
}
else if(dir==3){
for(int i=down;i>=top;i--)
ans.push_back(matrix[i][left]);
dir=0;
left++;
}
}
return ans;
}
};