54. Spiral Matrix

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]
vector<int> spiralOrder(vector<vector<int>>& matrix) { // time: O(m * n); space: O(m * n)
    if (matrix.empty()) return {};
    int m = matrix.size(), n = matrix[0].size();
    vector<int> res(m * n, 0);
    int idx = 0, up = 0, down = m - 1, left = 0, right = n - 1;
    while (true) {
        // top
        for (int col = left; col <= right; ++col) {
            res[idx++] = matrix[up][col];
        }
        if (++up > down) break;
        // right
        for (int row = up; row <= down; ++row) {
            res[idx++] = matrix[row][right];
        }
        if (--right < left) break;
        // down
        for (int col = right; col >= left; --col) {
            res[idx++] = matrix[down][col];
        }
        if (--down < up) break;
        // left
        for (int row = down; row >= up; --row) {
            res[idx++] = matrix[row][left];
        }
        if (++left > right) break;
    }
    return res;
}

Last updated

Was this helpful?