题目要求
解题思路
按照题目描述字面意思,从矩阵最外层开始向内层顺时针遍历。
两层循环嵌套,外层循环控制层数,内层循环遍历每层元素。
- 判断边界条件
- 通过左上角(top,left)和右下角(bottom,right)坐标位置限制每层的遍历范围
- 每层遍历
- 顶边:(top,left -> right),顶边的所有元素
- 右边:(top + 1 -> bottom,right),右边除第一个元素外所有元素
- 底边:(bottom,right - 1 -> left),底边除最右侧元素外所有元素
- 左边:(bottom - 1 -> top - 1,left),左边除第一个和最后一个元素外所有元素
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0)
{
return {};
}
vector<int> res;
int rows = matrix.size();
int cols = matrix[0].size();
int left = 0, right = cols - 1;
int top = 0, bottom = rows - 1;
while (left <= right && top <= bottom)
{
for (int j = left; j <= right; ++j)
{
res.push_back(matrix[top][j]);
}
for (int i = top + 1; i <= bottom; ++i)
{
res.push_back(matrix[i][right]);
}
if (left < right && top < bottom)
{
for (int j = right - 1; j >= left; --j)
{
res.push_back(matrix[bottom][j]);
}
for (int i = bottom - 1; i > top; --i)
{
res.push_back(matrix[i][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return res;
}
};