# 54. Spiral Matrix

## 刷题内容

• 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;
}
};