给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int rows = matrix.size();
if (rows == 0)return res;
int columns = matrix[0].size();
int start = 0;
while (columns > start * 2 && rows > start * 2) {
Print(matrix, columns, rows, start, res);
start++;
}
return res;
}
void Print(vector<vector<int>>& matrix, int columns, int rows, int start, vector<int>& res) {
int endX = columns - 1 - start;
int endY = rows - 1 - start;
//从左往右
for (int i = start; i <= endX; i++) {
res.push_back(matrix[start][i]);
}
//从上往下,前提是有两行或两行以上
//表现为endY 要大于start
if (start < endY) {
for (int i = start + 1; i <= endY; i++) {
res.push_back(matrix[i][endX]);
}
}
//从右往左,至少要两行两列
//表现为endY要大于start endX要大于start;
if (start < endX && start < endY) {
for (int i = endX - 1; i >= start; i--) {
res.push_back(matrix[endY][i]);
}
}
//从下往上, 至少要三行两列
//表现为endY - start > 1 && endX 》 start
if (endY - start > 1 && endX > start) {
for (int i = endY - 1; i > start; i--) {
res.push_back(matrix[i][start]);
}
}
}
};