从左至右、从上至下、从右到左、从下到上螺旋遍历一个二位数组,且数组长宽不一定相等。
思路
参考代码随想录中螺旋矩阵2$的思路,发现无法处理长宽非等长矩阵。
豆包的思路
- 从左至右:列++遍历,终止条件是行长度
- 从上到下:行++遍历,开始行需要+1,终止条件是行数量
- 从右到左:列--遍历,开始列需要-1,终止条件大于0
- 从下到上,行--遍历,开始行需要-1,终止条件大于0
每次循环这个四个操作,终止条件都需要收缩一下,就像四面墙不断收缩,因此可得:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.empty() || matrix[0].empty()) { return result; }
if (matrix.size() == 1 && !matrix[0].empty()) { return matrix[0]; };
int top = 0;
int bottom = matrix.size() - 1;
int left = 0;
int right = matrix[0].size() - 1;
int row = 0;
int col = 0;
while (top <= bottom && left <= right) {
// l -> r
for (col = left ; col <= right ; col++ ) {
result.emplace_back(matrix[left][col]);
}
top++;
for (row = top ; row <= bottom; row++ ) {
result.emplace_back(matrix[row][right]);
}
right--;
if (top <= bottom) {
for (col = right ; col >= left; col-- ) {
result.emplace_back(matrix[bottom][col]);
}
bottom--;
}
if (left <= right) {
for (row = bottom; row >= top; row-- ) {
result.emplace_back(matrix[row][left]);
}
left++;
}
}
return result;
}
};
``