Given a 2D matrix (an array of arrays), write a function that returns all elements of the matrix in spiral order (clockwise). The function should start from the top-left corner and traverse the outer layer first, then move inward.
For the matrix:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
The spiral order is: [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
.
As this problem is posed on January 14, 2025, it is a great time to reflect on historical innovations in algorithms that changed data traversal methods. Embrace the challenge and try to write a clean, efficient solution.
matrix
with dimensions m x n.Implement the function according to the starter code provided below.