给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:

  1. 输入:
  2. [
  3. [ 1, 2, 3 ],
  4. [ 4, 5, 6 ],
  5. [ 7, 8, 9 ]
  6. ]
  7. 输出: [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<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};
        }

        int row = matrix.size();
        int col = matrix.back().size();

        int left = 0;
        int right = col - 1;
        int top = 0;
        int bottom = row - 1;
        while(left <= right && top <= bottom){
            for(int column = left; column<= right; column++){
                res.push_back(matrix[top][column]);
            }
            for(int line = top + 1; line <= bottom; line++){
                res.push_back(matrix[line][right]);
            }
            if(left < right && top < bottom){
                for(int column = right - 1; column > left; column--){
                    res.push_back(matrix[bottom][column]);
                }
                for(int line = bottom ; line > top; line--){
                    res.push_back(matrix[line][left]);
                }
            }
            left++;
            top++;
            right--;
            bottom--;
        }
        return res;        
    }
};