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]
解:注意好上下左右的四个边界点即可
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty())
return {};
int row = matrix.size(),col = matrix[0].size();
int left = 0,right = col-1,up = 0,down = row - 1;
vector<int> res;
while(1)
{
//left to right
for(int i = left;i <= right;i++)
res.push_back(matrix[up][i]);
if(++up > down) break;
//up to down
for(int i = up; i <= down;i++ )
res.push_back(matrix[i][right]);
if(--right < left) break;
//right to left
for(int i = right;i >= left;i--)
res.push_back(matrix[down][i]);
if(--down < up) break;
//down to up
for(int i = down;i >= up;i--)
res.push_back(matrix[i][left]);
if(++left > right)
break;
}
return res;
}
};