Given a 2D array (matrix), write a function that returns all the elements of the matrix in spiral order (clockwise). This means starting from the top-left element and moving right, then down, then left, then up, and repeating this process until all elements have been included in the result.
For example, given the matrix:
[
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11,12]
]
The spiral order is: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
.
Groundhog Day (February 2nd) is a time for new beginnings and looking at things from a different perspective. Use this opportunity to make sure your algorithm covers all edge cases, just as we re-examine the seasons every year!
Example:
Input:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output:
[1, 2, 3, 6, 9, 8, 7, 4, 5]