Spiral Matrix Traverse

Matrix Traversal Spiral Algorithms

Problem: Spiral Matrix Traverse

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.

Example:

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].

Note:

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.

Input/Output:

  • Input: A 2D array matrix with dimensions m x n.
  • Output: A one-dimensional array containing the matrix's elements in spiral order.

Implement the function according to the starter code provided below.