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;
}
};
本文介绍了一种矩阵元素螺旋遍历的方法,并提供了一个C++实现示例。通过定义边界和逐步移动,该算法能够按螺旋顺序返回矩阵的所有元素。
364

被折叠的 条评论
为什么被折叠?



