/*
1.和54. 螺旋矩阵 一样,区别在于这里可能为空的矩阵,需要判断一下
思路:定义上下左右边界,模拟循环转圈,需要注意最后只剩一行或一列的时候需要添加额外的判断
因为每次都是先往右走和先往下走,所以往右走和往下走的路一定是没走过的路,不需要加 if 判断;往左走的时候,如果 top == bottom,那么会重复走之前从左往右走过的路,所以需要加上 top < bottom 的判断,同理往上走也一样。
*/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) return {}; //需要考虑矩阵为空的时候,难以想到
vector<int> result;
int rows = matrix.size(), colums = matrix[0].size();
//定义上下左右边界
int left = 0, right = colums - 1, top = 0, bottom = rows -1;
//做判断
if(rows == 0 || colums == 0) return result;
//开始循环便利
while(left <= right && top <= bottom){
for(int colum = left; colum <= right; colum++){
result.push_back(matrix[top][colum]);
}
for(int row = top + 1; row <= bottom; row++){
result.push_back(matrix[row][right]);
}
//难点在这,需要判断一下从右到左,从下到上的情况(单行或者单列的情况)
if(left < right && top < bottom)
{
for(int colum = right - 1; colum > left; colum--){
result.push_back(matrix[bottom][colum]);
}
for(int row = bottom; row > top; row--){
result.push_back(matrix[row][left]);
}
}
left++, right--;
top++, bottom--;
}
return result;
}
};
04-13
414
08-25
197