# C++ The onion we peel

• Peel the matrix by layer.

``````class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) return res;
if (matrix[0].empty()) return res;
int m = matrix.size(), n = matrix[0].size();
for (int layer = 0; layer < min(m + 1, n + 1) / 2; layer ++) peel(matrix, res, m, n, layer);
return res;
}
private:
void peel(vector<vector<int>>& matrix, vector<int>& res, int m, int n, int layer) {
int i = layer, j = layer;
if (m == 2 * layer + 1) {
for (; j < n - layer; j++) res.push_back(matrix[i][j]);
return;
}
if (n == 2 * layer + 1) {
for (; i < m - layer; i++) res.push_back(matrix[i][j]);
return;
}
for (; j < n - layer; j++) res.push_back(matrix[i][j]);
j--;
for (i++; i < m - layer; i++) res.push_back(matrix[i][j]);
i--;
for (j--; j >= layer; j--) res.push_back(matrix[i][j]);
j++;
for (i--; i > layer; i--) res.push_back(matrix[i][j]);
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.