# 0ms Clear C++ Solution

• The idea is just to add the elements in the spiral order. First the up-most row (`u`), then the right-most column (`r`), then the down-most row (`d`), and finally the left-most column (`l`). After finishing a row or a column, update the corresponding variable to continue the process.

The code is as follows.

``````class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) return {};
int m = matrix.size(), n = matrix[0].size();
vector<int> spiral(m * n);
int u = 0, d = m - 1, l = 0, r = n - 1, k = 0;
while (true) {
// up
for (int col = l; col <= r; col++) spiral[k++] = matrix[u][col];
if (++u > d) break;
// right
for (int row = u; row <= d; row++) spiral[k++] = matrix[row][r];
if (--r < l) break;
// down
for (int col = r; col >= l; col--) spiral[k++] = matrix[d][col];
if (--d < u) break;
// left
for (int row = d; row >= u; row--) spiral[k++] = matrix[row][l];
if (++l > r) break;
}
return spiral;
}
};``````

• so direct access is faster than push_back?

• @tjbstuff Yes, allocating spaces in advance is faster.

• really clean and clear !

• effective and concise