算法-矩阵-螺旋矩阵(按层模拟)_java

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
//若空
if(matrix.size() == 0 || matrix[0].size() == 0) return {};
//行列
int rows = matrix.size(), columns = matrix[0].size();
//定义top,bottom,left,right
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
vector<int> order;
//循环
while(left <= right && top <= bottom){
for(int column = left; column < right; column++){
order.push_back(matrix[top][column]);
}
for(int row = top ; row <= bottom; row++){
order.push_back(matrix[row][right]);
}
if(left < right && top < bottom){
for(int column = right - 1; column >= left; column--){
order.push_back(matrix[bottom][column]);
}
for(int row = bottom - 1; row > top; row--){
order.push_back(matrix[row][left]);
}
}
left++;
top++;
right--;
bottom--;
}
return order;
}
};