Spiral Matrix
Medium · matrix
You are given a grid of integers matrix with m rows and n columns. Read every value in a clockwise spiral: start at the top-left cell and move right along the top row to its end, then down the right-hand column, then left along the bottom row, then up the left-hand column. Keep winding inwards in the same way until every cell has been read exactly once.
Return the values as a list, in the order you read them. The list has m * n values.
Examples
Example 1
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Right along 1, 2, 3, down through 6, 9, left through 8, 7, up to 4, and finally the middle cell 5.
Example 2
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]
After the outer ring, the inner row 6, 7 is read left to right.
Example 3
Input: matrix = [[7], [8], [9]]
Output: [7, 8, 9]
With one column there is nothing to wind around, so the values are read from top to bottom.
Constraints
- 1 <= m, n <= 200
- -1000 <= matrix[i][j] <= 1000