sagelearnai

Spiral Matrix

Difficulty: Medium · Pattern: Matrix · LeetCode #54

Return all elements of an m × n matrix in spiral order: clockwise, starting from the top-left.

Examples

text
[[1,2,3],[4,5,6],[7,8,9]]          →  [1,2,3,6,9,8,7,4,5]
[[1,2,3,4],[5,6,7,8],[9,10,11,12]] →  [1,2,3,4,8,12,11,10,9,5,6,7]

Hints

  1. Keep four boundaries. Traverse the top row, then the right column, then the bottom row, then the left column, shrinking each boundary after you use it.
  2. For non-square matrices, check that the boundaries are still valid before the bottom and left passes.

Approach

text
top, bottom, left, right = 0, m-1, 0, n-1
while top <= bottom and left <= right:
    left→right on row top;      top += 1
    top→bottom on col right;    right -= 1
    if top <= bottom: right→left on row bottom; bottom -= 1
    if left <= right: bottom→top on col left;   left += 1

The two if guards prevent re-reading a row or column when the remaining region is a single row or column. Forgetting them is the classic bug.

Complexity

Time: O(m·n). Space: O(1) besides the output.

Python solution
def spiralOrder(matrix):
    res = []
    top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
    while top <= bottom and left <= right:
        res += matrix[top][left:right + 1]
        top += 1
        res += [matrix[r][right] for r in range(top, bottom + 1)]
        right -= 1
        if top <= bottom:
            res += matrix[bottom][left:right + 1][::-1]
            bottom -= 1
        if left <= right:
            res += [matrix[r][left] for r in range(bottom, top - 1, -1)]
            left += 1
    return res
JavaScript solution
function spiralOrder(matrix) {
  const res = [];
  let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
  while (top <= bottom && left <= right) {
    for (let c = left; c <= right; c++) res.push(matrix[top][c]);
    top++;
    for (let r = top; r <= bottom; r++) res.push(matrix[r][right]);
    right--;
    if (top <= bottom) { for (let c = right; c >= left; c--) res.push(matrix[bottom][c]); bottom--; }
    if (left <= right) { for (let r = bottom; r >= top; r--) res.push(matrix[r][left]); left++; }
  }
  return res;
}