0ms Clear C++ Solution


  • 71

    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;
        }
    };

  • 0
    K

    so direct access is faster than push_back?


  • 0

    @tjbstuff Yes, allocating spaces in advance is faster.


  • 0

    really clean and clear !


  • 0
    C

    effective and concise


  • 0
    O

    Enjoyed reading this code


Log in to reply
 

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