Spiral Matrix
Given an m x n matrix matrix, return all elements of the matrix in spiral order.
Spiral order means traversing the matrix by repeatedly moving:
- From left to right across the current top row.
- From top to bottom down the current right column.
- From right to left across the current bottom row, if it has not already been visited.
- From bottom to top up the current left column, if it has not already been visited.
Continue this process inward until every element has been included in the returned list.
Example 1
1 2 3 4 5 6 7 8 9
Input
matrix = [[1,2,3],[4,5,6],[7,8,9]]Output
[1,2,3,6,9,8,7,4,5]The traversal visits the top row, then the right column, then the bottom row in reverse, and finally the remaining center element.
Example 2
1 2 3 4 5 6 7 8 9 10 11 12
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]The traversal goes around the outside of the rectangular matrix, then visits the remaining inner elements from left to right.
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100