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]

思路:设置四个边界,直接 一圈一圈转就OK了。

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int>re;
        if(matrix.empty() || matrix[0].empty()) return re;
        int l=0, r=matrix[0].size()-1, up=0, low=matrix.size()-1;
        while(l<=r && up<=low){
            for(int j=l; j<=r; ++j)
                re.push_back(matrix[up][j]); 
            for(int i=up+1; i<=low; ++i)
                re.push_back(matrix[i][r]);
            for(int j=r-1; low>up && j>=l; --j)
                re.push_back(matrix[low][j]);
            for(int i=low-1; r>l && i>up; --i)
                re.push_back(matrix[i][l]);
            ++l,  --r, ++up, --low;
        }
        return re;
    }
};

猜你喜欢

转载自blog.csdn.net/scarlett_guan/article/details/80235092