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] |
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 示例 1: 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5] 示例 2: 输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7] |
思路:4个指针。left,right,up,down;分别遍历后移动。 注意边界值情况。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty() || matrix[0].empty()) return {};
int rowi=0,rowj=matrix.size()-1;
int coli=0,colj=matrix[0].size()-1;
vector<int> res;
while(rowi<=rowj && coli<=colj)
{
for(int i=coli;i<=colj;++i)
res.push_back(matrix[rowi][i]);
if(++rowi>rowj) break;
for(int i=rowi;i<=rowj;++i)
res.push_back(matrix[i][colj]);
if(--colj<coli) break;
for(int i=colj;i>=coli;--i)
res.push_back(matrix[rowj][i]);
if(--rowj<rowi) break;
for(int i=rowj;i>=rowi;--i)
res.push_back(matrix[i][coli]);
if(++coli>colj) break;
}return res;
}
};