[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; } };
相关文章推荐
- 【LeetCode】Search a 2D Matrix & Set Matrix Zeroes & Spiral Matrix & Spiral Matrix II
- LeetCode 59 - Spiral Matrix II
- LeetCode 059 Spiral Matrix II
- LeetCode Spiral Matrix
- LeetCode 59 Spiral Matrix II
- leetcode-Spiral Matrix
- LeetCode——Spiral Matrix
- leetcode——Spiral Matrix
- 【leetcode】 Spiral Matrix
- Leetcode Spiral Matrix II
- LeetCode 059 Spiral Matrix II
- leetcode -- Spiral Matrix -- 思路简单,但很麻烦
- [LeetCode]Spiral Matrix@python
- leetcode--Spiral Matrix II
- LeetCode---Spiral Matrix II
- 【C++】【LeetCode】54. Spiral Matrix && 59. Spiral Matrix II
- LeetCode: Spiral Matrix 解题报告
- 牛客:剑指offer:顺时针打印矩阵 (Java)(同leetcode的spiral matrix i 和ii)
- leetcode 80: Spiral Matrix
- [LeetCode] Spiral Matrix II