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].
Subscribe to see which companies asked this questionclass Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int len = matrix.size();
vector<int> ret;
if(len == 0) return ret;
int rows = len, cols = matrix[0].size();
int beginRow=0, endRow=rows-1, beginCol=0, endCol=cols-1;
for(; beginRow <= endRow && beginCol <= endCol; beginRow++, endRow--, beginCol++, endCol--) {
int tmpCol = beginCol;
while(tmpCol <= endCol) {
ret.push_back(matrix[beginRow][tmpCol]);
tmpCol++;
}
int tmpRow = beginRow+1;
while(tmpRow <= endRow) {
ret.push_back(matrix[tmpRow][endCol]);
tmpRow++;
}
tmpCol = endCol-1;
while(tmpCol >= beginCol && endRow > beginRow) {
ret.push_back(matrix[endRow][tmpCol]);
tmpCol--;
}
tmpRow=endRow-1;
while(tmpRow > beginRow && endCol > beginCol) {
ret.push_back(matrix[tmpRow][beginCol]);
tmpRow--;
}
}
return ret;
}
};
本文介绍了一种矩阵螺旋遍历的算法实现,该算法能够按螺旋顺序返回给定矩阵的所有元素。通过定义边界并逐步缩小处理范围的方式实现了螺旋遍历的过程。
1142

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



