Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]
.
没啥特别的方法,按照顺序进行模拟,注意好边界值的判断。
代码如下:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if(matrix.empty())
return result;
int m = matrix.size();
int n = matrix[0].size();
int rowbegin=0,colbegin=0;
int rowend=m-1,colend=n-1;
while(rowbegin <= rowend && colbegin <= colend)
{
for(int i=colbegin;i <= colend;i++)
{
result.push_back(matrix[rowbegin][i]);
}
rowbegin++;
for(int i = rowbegin;i <= rowend;i++)
{
result.push_back(matrix[i][colend]);
}
colend--;
if(rowbegin <= rowend)//经过前面语句会导致rowbegin>rowend
{
for(int i = colend;i>=colbegin;i--)
{
result.push_back(matrix[rowend][i]);
}
rowend--;
}
if(colbegin <= colend)//经过前面语句会导致colbegin>colend
{
for(int i = rowend;i>=rowbegin;i--)
{
result.push_back(matrix[i][colbegin]);
}
colbegin++;
}
}
return result;
}
};