Skip to content

0054. Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

img

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

img

Input: matrix = [[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]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Analysis

Split the matrix into four parts: 1. right: column can move in the range of [l, r], after finish, ++u 2. down: row can move in the range of [u, d], after finish, --r 3. left: column can move in the range of [l, r], after finish, ++d 4. up: row can move in the range of [u, d], after finish, ++l

Code

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

Last update: April 1, 2022