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]
注意只有一行或者只有一列的情况
if (r1 < r2 && c1 < c2) {//避免只有一行,c1==c2的情况,避免只有一列,r1==r2的情况
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> list ;
if(matrix.size()==) return list;
int rows =matrix.size();
int cols = matrix[].size();
int c1 = ,c2 = cols-;
int r1 = ,r2 = rows-; while(r1<=r2&&c1<=c2){
for(int c=c1;c<=c2;c++) list.push_back(matrix[r1][c]);
for(int r=r1+;r<=r2;r++) list.push_back(matrix[r][c2]);
if (r1 < r2 && c1 < c2) {//避免只有一行,c1==c2的情况,避免只有一列,r1==r2的情况
for(int c=c2-;c>=c1+;c--) list.push_back(matrix[r2][c]);
for(int r=r2;r>=r1+;r--) list.push_back(matrix[r][c1]);
}
c1++;c2--;r1++;r2--;
}
return list;
}
};
还没有评论呢,快来抢沙发~