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

思路

  1. 没啥问题,以前做过了的话,有手就行
  2. 设置边界,模拟就行了,每遍历一行都需要判断是否已经完成了
  3. 注意一下边界即可

代码

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int left = 0, right = matrix[0].size()-1, top = 0, bottom = matrix.size()-1;
        vector<int> ans;
        while(left <= right || top <= bottom){
            for(int i = left; i < right+1; ++i)
                ans.push_back(matrix[top][i]);
            if(++top > bottom) break;
            for(int i = top; i < bottom+1; ++i)
                ans.push_back(matrix[i][right]);
            if(--right < left) break;
            for(int i = right; i > left-1; --i)
                ans.push_back(matrix[bottom][i]);
            if(--bottom < top) break;
            for(int i = bottom; i > top-1; --i)
                ans.push_back(matrix[i][left]);
            if(++left > right) break;
        }
        return ans;
    }
};
posted @ 2020-12-10 07:04  肥斯大只仔  阅读(37)  评论(0编辑  收藏  举报