Leetcode 54. Spiral Matrix
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]
思路:用一个变量记录要打印的圈数
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int row,col;
row=matrix.size();
if(row ==0) return res;
col=matrix[0].size();
int circles=((row<col?row:col)-1)/2+1;
for(int k=0;k<circles;k++){
for (int i=k;i<col-k;i++) res.push_back(matrix[k][i]);
for (int j=k+1;j<row-k;j++) res.push_back(matrix[j][col-1-k]);
for (int m=col-k-2;(m>=k) && (row-k-1!=k);m--) res.push_back(matrix[row-k-1][m]);
for (int n=row-k-2;(n>k) && (col-k-1!=k);n--) res.push_back(matrix[n][k]);
}
return res;
}
};