Problem 322619 · medium · Level 03 Linear Management & Searching

Spiral Matrix

matrix · simulation · arrays

Matrix problems are mostly about keeping careful bounds. Walking a matrix in a spiral means: go right along the top row, down the right column, left along the bottom row, up the left column, then shrink all four boundaries and repeat.

Given an m x n matrix (a list of lists), return a flat list of all its elements in clockwise spiral order starting from the top-left corner.

Examples

Input:  matrix = [[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
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

  • 1 <= m, n <= 50
  • The matrix may be a single row, a single column, or non-square.
  • Aim for O(m * n) time: every element is visited exactly once.

Goals

  • Track four shrinking boundaries (top, bottom, left, right) while walking a matrix
  • Traverse a row or column in the right direction with range()
  • Guard against re-visiting a row or column when the remaining region is one row or column tall
Starting Python…