Menu
CoddyTech

Spiral Matrix

You get a matrix of integers with m rows and n columns, given as a list of rows. Return all of its values in spiral order.

Start at the top-left corner and go right along the top row, then down the right column, left along the bottom row and up the left column. Keep circling inward clockwise until every value has been read exactly once.

Function

spiralOrder(matrix: integer-2d-array) → integer-array
matrixinteger-2d-array
the grid of integers, as a list of rows of equal length
Returnsinteger-array
every value of the matrix in clockwise spiral order, starting at the top-left corner

Constraints

  • 1 ≤ m, n ≤ 80, where m = matrix.length and n = matrix[i].length
  • Every row has the same length n.
  • -100 ≤ matrix[i][j] ≤ 100

Examples

Input
matrix = [[1, 2, 3], [10, 11, 4], [9, 12, 5], [8, 7, 6]]
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Explanation
The values count up along the spiral. The outer ring reads 1, 2, 3 along the top, 4, 5, 6 down the right, 7, 8 back along the bottom and 9, 10 up the left. The inner layer is a single column, read once from top to bottom: 11, 12.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Can you return the values in counterclockwise order instead, starting at the top-left corner and going down the left column first?

Reset code
def spiralOrder(matrix):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

matrix = [[1, 2, 3], [10, 11, 4], [9, 12, 5], [8, 7, 6]]

Expected

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