Arrays and Hashing Walking a matrix
83. Spiral Matrix
You are given a matrix of integers matrix with m rows and n columns. Return all of its values in
spiral order.
Spiral order starts at the top-left cell and moves right along the top row. At the end of the row it turns and goes down the right column, then left along the bottom row, then up the left column. It keeps turning clockwise in the same way, ring by ring toward the centre, until it has read every cell once.
Example 1
Input: matrix = [[3, 8, -1, 6],
[0, 7, 4, -5],
[9, 2, 10, 1]]
[3,8,-1,6,-5,1,10,2,9,0,7,4]Explanation: The outer ring gives 3, 8, −1, 6 along the top, −5, 1 down the right, 10, 2, 9 back along the bottom and 0 up the left. Only the inner part of the middle row is left, so the spiral ends with 7 and 4.
Example 2
Input: matrix = [[5], [-2], [8]]
[5,-2,8]Explanation: With a single column, the spiral reads the top cell and then goes straight down. There is nothing to the left or the right to come back along.
Example 3
Input: matrix = [[4, -7, 1],
[0, 9, 3],
[-1000000000, 6, 1000000000]]
[4,-7,1,3,1000000000,6,-1000000000,0,9]Explanation: The outer ring holds eight values. The centre cell, 9, is a ring of its own and comes last.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
m == matrix.length, and every row hasnvalues1 ≤ m, nandm × n ≤ 105-109 ≤ matrix[i][j] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.