Practice · Math and matrices · 1 of 3

Read a Matrix in a Spiral

You are given matrix, a grid of integers with m rows and n columns.

Return all of its values in spiral order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row and up the left column, then carry on the same way round the part not yet read, until every value is listed exactly once.

Example 1

Input
matrix = [[1, 2, 3, 4], [10, 11, 12, 5], [9, 8, 7, 6]]
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Read in spiral order, this grid counts from 1 to 12.

Example 2

Input
matrix = [[1, 2], [3, 4], [5, 6]]
Output
[1, 2, 4, 6, 5, 3]

Constraints

  • 1 ≤ m, n ≤ 20
  • −1000 ≤ matrix[r][c] ≤ 1000