Type:medium
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]
将给定vector<vector<int>>按照螺旋状输出,可将其一圈一圈输出,将一圈输出视为一次循环。循环次数为matrix.size()和matrix[0].size()的最小值除以2。对于每一圈数值,每次循环依次输出:从左到右、从上到下,从右到左、从下到上。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty() || matrix[0].empty()) return {};
int n = matrix.size();
int m = matrix[0].size();
int c = m>n? n/2:m/2;
vector<int> ret;
for(int i=0; i<c; i++){
for(int j=i; j<=m-i-1; j++){
ret.push_back(matrix[i][j]);
}
for(int j=i+1; j<=n-i-1; j++){
ret.push_back(matrix[j][m-i-1]);
}
for(int j=m-i-2; j>=i; j--){
ret.push_back(matrix[n-i-1][j]);
}
for(int j=n-i-2; j>=i+1; j--){
ret.push_back(matrix[j][i]);
}
}
if((m>n? n:m) % 2 == 0) return ret;
if(m>n){
for(int i=c; i<=m-c-1; i++){
ret.push_back(matrix[c][i]);
}
return ret;
}
if(n>m){
for(int i=c; i<=n-c-1; i++){
ret.push_back(matrix[i][c]);
}
return ret;
}
if(n==m){
ret.push_back(matrix[c][c]);
return ret;
}
return ret;
}
};