给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
其核心问题在于:
- 遍历多少圈:
(min(m, n) + 1) / 2
- 最后一个数如何处理:特殊处理
- 什么时候遍历完成:必须实时判定,以防最后一圈遍历两次
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
//空矩阵处理,一定先判定matrix.size()=0,否则越界
if(matrix.size() == 0 || matrix[0].size() == 0){
return {};
}
int m = matrix.size(), n = matrix[0].size(); //初始化行数和列数
int start_x = 0, start_y = 0; //每圈开始坐标
int offset = 1; //每边结束偏移
int x = 0, y = 0; //实时遍历坐标
int index = 0; //遍历序号
int loop = (min(m, n) + 1) / 2; //遍历圈数
vector<int> res(m*n, 0); //结果
while(loop--){ //按圈遍历
x = start_x; //实时坐标=每圈初始坐标
y = start_y;
if(n==m && n%2 == 1 && loop == 0){ //最后一个数判定
res[index] = matrix[x][y]; //最后一个数处理
}
for(y ; y < n - offset; y++){ //上边遍历
if(index == m*n) return res; //遍历结束判定
res[index++] = matrix[x][y]; //遍历处理
}
for(x; x < m - offset; x++){ //左边遍历
if(index == m*n) return res;
res[index++] = matrix[x][y];
}
for(y; y > start_y; y--){ //下边遍历
if(index == m*n) return res;
res[index++] = matrix[x][y];
}
for(x; x > start_x; x--){ //右边遍历
if(index == m*n) return res;
res[index++] = matrix[x][y];
}
start_x++; //更新圈起始坐标
start_y++;
offset++; //更边偏移
}
return res;
}
};