Skip to content

54. Spiral Matrix

难度:Medium

刷题内容

原题连接

  • https://leetcode.com/problems/spiral-matrix/submissions/

内容描述

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

˼·1 *- ʱ¼ä¸´ÔÓ¶È: O(nm)*- ¿Õ¼ä¸´ÔÓ¶È: O(1)***

ÂÝÐý±éÀúÊý×飬ÕÒµ½¹æÂɾÍÐУ¬ºÃÏñûʲô难度

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ans;
        if(!matrix.size())
            return ans;
        int row = matrix[0].size(),colunm = matrix.size();
        for(int i = 0;i < (matrix.size() + 1) / 2;++i)
        {
            if(row < 1 || colunm < 1)
                break;
            for(int j = 0;j < row;++j)
                ans.push_back(matrix[i][i + j]);
            if(colunm <= 1)
                break;
            for(int j = 1;j < colunm;++j)
                ans.push_back(matrix[i + j][row + i - 1]);
            if(row <= 1)
                break;
            for(int j = 1;j < row;++j)
                ans.push_back(matrix[i + colunm - 1][row + i - 1 - j]);
            for(int j = 1;j < colunm - 1;++j)
                ans.push_back(matrix[i + colunm - 1 - j][i]);
            row -= 2;
            colunm -= 2;
        }
        return ans;
    }
};


回到顶部