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.
1 class Solution { 2 public: 3 vector spiralOrder(vector>& matrix) { 4 if (matrix.empty()) return {}; 5 int m = matrix.size(), n = matrix[0].size(); 6 vector spiral(m * n); 7 int u = 0, d = m - 1, l = 0, r = n - 1, k = 0; 8 while (true) { 9 // up10 for (int col = l; col <= r; col++) spiral[k++] = matrix[u][col];11 if (++u > d) break;12 // right13 for (int row = u; row <= d; row++) spiral[k++] = matrix[row][r];14 if (--r < l) break;15 // down16 for (int col = r; col >= l; col--) spiral[k++] = matrix[d][col];17 if (--d < u) break;18 // left19 for (int row = d; row >= u; row--) spiral[k++] = matrix[row][l];20 if (++l > r) break;21 }22 return spiral;23 }24 };