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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int startx,starty,endx,endy;
vector<int> ret;
if(matrix.size()==0)
return ret;
startx=0,starty=0,endx=matrix.size()-1,endy=matrix[0].size()-1;
for(; startx<=endx && starty<=endy ; startx++,starty++, endx--,endy--){
for(int i=starty ; i<=endy ; i++)
ret.push_back(matrix[startx][i]);
for(int j=startx+1 ; j<=endx ; j++)
ret.push_back(matrix[j][endy]);
if(startx!=endx){
for(int k=endy-1 ; k>=starty ; k--)
ret.push_back(matrix[endx][k]);
}
if(starty!=endy){
for(int l=endx-1 ; l>startx ; l--)
ret.push_back(matrix[l][starty]);
}
}
return ret;
}
};
本文介绍了一种矩阵螺旋遍历算法的实现方法,通过定义起始和结束边界,逐层遍历矩阵元素,并按螺旋顺序返回所有元素。适用于m x n矩阵。
1161

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



