tags: review
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) {
if (matrix.empty() || matrix[0].empty())
return vector<int>();
vector<int> res;
int m = matrix.size();
int n = matrix[0].size();
int layer = 0;
int i = 0, j = 0;
while(layer <= (min(m,n)-1)/2) {
res.push_back(matrix[i][j]);
// to right
if (j < n - layer) {
j++;
while(j < n - layer) {
res.push_back(matrix[i][j]);
j++;
}
j--;
}
// to bottom
if (i >= m - 1 - layer)
break;
i++;
while (i < m - layer) {
res.push_back(matrix[i][j]);
i++;
}
i--;
// to left
if (j <= layer)
break;
j--;
while (j >= layer) {
res.push_back(matrix[i][j]);
j--;
}
j++;
// to top
if (i <= layer)
break;
i--;
while (i > layer) {
res.push_back(matrix[i][j]);
i--;
}
layer++;
i = layer;
j = layer;
}
return res;
}
};