【Leetcode题解】Leetcode 54:螺旋矩阵Ⅰ

Leetcode 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]

整体思路是按题目要求模拟,顺时针转,先从左到右,再从上到下
最后从右到左,从下到上,注意点在于边界值控制

class Solution {
public:
   vector spiralOrder(vector>& matrix) {
      if(matrix.empty() || matrix[0].empty())
      {
          return {};
      }
      int m = matrix.size();
      int n = matrix[0].size();

      int up = 0,left = 0;
      int down = m-1,right = n-1;

      ventor res;

      while(up<=down && left<=right)
      {
          for(int i = left;i <= right;i++)    // 注意<= [left,right]
          {
              res.push_back(matrix[up][i]);
          }
          for(int i = up + 1;i <= down;i++)   //注意+1 <= (up,down]
          {
              res.push_back(matrix[i][right]);
          }
          if(up left;i--)  //[right,left)
              {
                   res.push_back(matrix[down][i]);
              }
              for(int i = down;i > up;i--)        //(down,up)
              {
                   res.push_back(matrix[i][left]);
              }
          }
      }
       return res;
   }

};

你可能感兴趣的:(LeetCode,题解)