SDE & MLE Prep

54. Spiral Matrix

Problem

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

Example: [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5]

Walk right along top, down along right, left along bottom, up along left, shrinking each boundary after use. Guard the last two walks for single rows/columns.

 1 →  2 →  3 →  4
                 ↓
 5 →  6 →  7     8        order: 1 2 3 4 8 12 11 10 9 5 6 7
 ↑               ↓
 9 ← 10 ← 11 ← 12

Complexity: O(m·n).

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
        while top <= bottom and left <= right:
            res += [matrix[top][c] for c in range(left, right + 1)]
            res += [matrix[r][right] for r in range(top + 1, bottom + 1)]
            if top < bottom and left < right:
                res += [matrix[bottom][c] for c in range(right - 1, left - 1, -1)]
                res += [matrix[r][left] for r in range(bottom - 1, top, -1)]
            top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1
        return res