Spiral Matrix

MediumMatrix

You get an m × n matrix. Return all of its values in spiral order: start at the top left and go clockwise, along the top row, down the right column, back along the bottom row, up the left column, then the same again one ring further in, until every value is read once.

Examples

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

The numbers are laid out so the spiral reads them in order: the outer ring 1 to 8, then the 9 in the middle.

Example 2
Input:  matrix = [[3, 1], [4, 1], [5, 9]]
Output: [3, 1, 1, 9, 5, 4]

Across the top (3, 1), down the right (1, 9), back along the bottom (5), up the left (4).

Constraints

  • 1 ≤ m, n ≤ 10
  • -100 ≤ matrix[i][j] ≤ 100

Stuck?

Hint 1

Keep four bounds: the top row, the bottom row, the left column and the right column still unread. Read one side, then move that bound inward.

Hint 2

After reading the top row and the right column, check that a row and a column are still left before reading the bottom row and the left column backwards. Without that check, a matrix with a single row or column left is read twice.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur