您的位置:首页 > 其它

[Leetcode] Spiral Matrix

2016-12-28 14:58 323 查看

描述

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: