当前位置:   article > 正文

2020-10-31 54.螺旋矩阵

螺旋矩阵

54. 螺旋矩阵

给定一个包含 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]

 左神方法的的C++写法

  1. class Solution {
  2. public:
  3. vector<int> spiralOrder(vector<vector<int>>& matrix) {
  4. vector<int> res;
  5. if(matrix.empty()) {
  6. return res;
  7. }
  8. int startRow = 0, startCol = 0;
  9. int endRow = matrix.size() - 1, endCol = matrix[0].size() - 1;
  10. while(startRow <= endRow && startCol <= endCol) {
  11. circleMatrix(matrix, res, startRow++, startCol++, endRow--, endCol--);
  12. }
  13. return res;
  14. }
  15. void circleMatrix(vector<vector<int>>& matrix, vector<int>& res, int startRow, int startCol, int endRow, int endCol) {
  16. if(startRow == endRow) {
  17. for(int i = startCol; i <= endCol; i ++) {
  18. res.push_back(matrix[startRow][i]);
  19. }
  20. } else if(startCol == endCol) {
  21. for(int i = startRow; i <= endRow; i ++) {
  22. res.push_back(matrix[i][startCol]);
  23. }
  24. } else {
  25. for(int curCol = startCol; curCol < endCol; curCol++) {
  26. res.push_back(matrix[startRow][curCol]);
  27. }
  28. for(int curRow = startRow; curRow < endRow; curRow++) {
  29. res.push_back(matrix[curRow][endCol]);
  30. }
  31. for(int curCol = endCol; curCol > startCol; curCol--) {
  32. res.push_back(matrix[endRow][curCol]);
  33. }
  34. for(int curRow = endRow; curRow > startRow; curRow--) {
  35. res.push_back(matrix[curRow][startCol]);
  36. }
  37. }
  38. }
  39. };

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/848235
推荐阅读
相关标签
  

闽ICP备14008679号