描述
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]
.
将一个二维数组以螺旋遍历的方式输出。
分析
这道题没有什么比较好的方法,只能由外到内,每次输出最外面一圈的数字,需要提前计算好输出的次数。
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
vector<int> res;
int m = matrix.size(), n = matrix[0].size();
int row = -1, col = -1, count = min((m + 1) / 2,(n + 1) / 2), run = 0;
while (run < count) {
if (res.size() == m * n) break;
for (row++, col++; col < n - run; col++) res.push_back(matrix[row][col]);
for (row++, col--; row < m - run; row++) res.push_back(matrix[row][col]);
if (res.size() == m * n) break;
for (col--, row--; col >= run; col--) res.push_back(matrix[row][col]);
for (row--, col++; row > run; row--) res.push_back(matrix[row][col]);
run++;
}
return res;
}
};